我在下面的布局中需要表示我的数据,然后最终需要从中制作一个字节数组。
// 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
如何使用字节缓冲区将其表示在一个字节数组中?任何简单的例子都可以帮助我更好地理解。
最佳答案
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();
关于java - 如何使用字节缓冲区在一个字节数组中表示数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26446132/