2014-10-19 38 views
0

我有我的下面的佈局,我需要代表我的數據,然後最後我需要做出一個字節數組。如何使用字節緩衝區在一個字節數組中表示數據?

// 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 

如何代表這在使用字節緩衝一個字節數組?任何簡單的例子都會幫助我更好地理解。

回答

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(); 
+0

感謝gharma的幫助。你能解釋我如何計算'totalSize'嗎?只是有點混淆。 – john 2014-10-19 05:34:15

+0

totalSize應該等於最終byteArray中的總字節數。因此,keyType爲1個字節,keyLength爲1個字節,密鑰爲個字節,時間戳爲8個字節,dataSize爲2個字節,數據爲個字節。 – gharrma 2014-10-20 03:15:25

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