如何使用字节缓冲区在一个字节数组中表示数据?

时间:2014-10-19 00:51:19

标签: java bytearray bytebuffer endianness

我有下面的布局,我需要在其中表示我的数据,然后最后我需要制作一个字节数组。

// below is my data layout -
// data key type which is 1 byte
// data key len which is 1 byte
// data key (variable size which is a key_len)
// timestamp (sizeof uint64_t)
// data size (sizeof uint16_t)
// data (variable size = data size)

所以我开始这样,但我有一些困惑,所以卡住了 -

// data layout
byte dataKeyType = 101;
byte dataKeyLength = 3;

// not sure how to represent key here

long timestamp = System.currentTimeMillis(); // which is 64 bit
short dataSize = 320; // what does this mean? it means size of data is 320 bytes?

// and now confuse as well how to represent data here, we can have any string data which can be converted to bytes


// and then make final byte array out of that

如何使用字节缓冲区在一个字节数组中表示?任何简单的例子都会帮助我更好地理解。

2 个答案:

答案 0 :(得分:1)

您可以使用Java的DataOutputStream类来动态生成字节数组。例如:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);

dos.writeByte(keyType);
dos.writeByte(keyLength);
dos.write(new byte[] { 1, 2, 3, ..., key_len-1 }, 0, key_len);
dos.writeLong(System.currentTimeMillis());
dos.writeShort(320);
dos.write(new byte[] { 1, 2, 3, ..., 319 }, 0, 320);

您应该分别用包含关键字节的数组和包含数据的数组替换两个new byte[] {}部分。

答案 1 :(得分:1)

    byte keyType = 101;
    byte keyLength = 3;
    byte[] key = {27, // or whatever your key is
                  55, 
                  111};
    long timestamp = System.currentTimeMillis();

    // If your data is just a string, then you could do the following.
    // However, you will likely want to provide the getBytes() method
    // with an argument that specifies which text encoding you are using.
    // The default is just the current platform's default charset.
    byte[] data = "your string data".getBytes();
    short dataSize = (short) data.length;

    int totalSize = (1 + 1 + keyLength + 8 + 2 + dataSize);
    ByteBuffer bytes = ByteBuffer.allocate(totalSize);

    bytes.put(keyType);
    bytes.put(keyLength);
    bytes.put(key);
    bytes.putLong(timestamp);
    bytes.putShort(dataSize);
    bytes.put(data);

    // If you want everthing as a single byte array:
    byte[] byteArray = bytes.array();