簡體   English   中英

如何使用字節緩沖區在一個字節數組中表示數據?

[英]How to represent data in one byte array using Byte Buffer?

我在下面的布局中需要表示自己的數據,然后最終需要從中制作一個字節數組。

// 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的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[] {}部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM