2012-12-05 66 views
0

我想連接long和bytearray到另一個bytearray。連接long和bytearray到另一個bytearray

我想是這樣的:

byte[] value1= new byte[16]; 
byte[] value2= new byte[16]; 
byte[] finalvalue = new byte[value1.length + value2.length]; 
long ts = System.currentTimeMillis(); 
int val = 100; 

ByteBuffer.wrap(value1).order(ByteOrder.LITTLE_ENDIAN).asLongBuffer().put(ts); 
ByteBuffer.wrap(value2).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().put(val); 

System.arraycopy(value1, 0, finalvalue, 0, value1.length); 
System.arraycopy(value2, 0, finalvalue, value1.length,value2.length); 

當我試圖把它打印出來,我沒有得到正確的價值觀。它打印這樣

BYTEVALUE -95-15-4410659100000000002000000000000000 

它應該打印這樣

- BYTEVALUE- 1354707038625,100 

誰能幫我在哪裏,我錯了。

幫助將不勝感激。

更新:

使用使用打印值的StringBuffer這樣的:

StringBuffer sb = new StringBuffer(finalvalue.length); 
for (int i = 0; i < finalvalue.length; i++) { 
    sb.append(finalvalue[i]); 
} 
+5

顯示用於打印輸出的代碼。 – Jesper

+0

我不確定,只是猜測,是因爲它超過了「字節」限制或什麼? –

+0

@Jesper更新了問題 –

回答

2

你的代碼是不是做你認爲它是。請看下面的獨立的應用程序:

import java.nio.ByteBuffer; 
import java.nio.ByteOrder; 

public class ByteArrayTest { 

    public static void main(String[] args) { 
    byte[] value1 = new byte[16]; 
    byte[] value2 = new byte[16]; 
    byte[] finalvalue = new byte[value1.length + value2.length]; 
    long ts = System.currentTimeMillis(); 
    int val = 100; 

    ByteBuffer.wrap(value1).order(ByteOrder.LITTLE_ENDIAN).asLongBuffer() 
     .put(ts); 
    ByteBuffer.wrap(value2).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer() 
     .put(val); 

    System.arraycopy(value1, 0, finalvalue, 0, value1.length); 
    System.arraycopy(value2, 0, finalvalue, value1.length, value2.length); 

    printByteArray(finalvalue); 
    } 

    private static void printByteArray(final byte[] array) { 
    StringBuilder sb = new StringBuilder(array.length); 
    for (byte b : array) { 
     sb.append(String.format("%02X", b)); 
    } 
    System.out.println(sb.toString()); 
    } 
} 

的這個輸出是:

BE26086B3B010000000000000000000064000000000000000000000000000000 

拆分成各個組成部分,我們可以看到,爲什麼:

  • 前十六個字節是BE26086B3B0100000000000000000000。這是您的小尾數順序的時間戳。如果忽略零字節,則這將轉換爲十進制的1,354,710,394,558,這是正確的。

  • 第二十六個字節是64000000000000000000000000000000,這是您的硬編碼值100

零表示您沒有使用的字節數組中的空格。