2015-06-03 71 views
0

我遇到問題,該方法無法按預期工作。在大多數情況下,它的作品但是有一種情況不起作用。 我有一個包含一些值的字節數組。在十六進制例如:0x04 0x42(littleEndian)。如果我使用convertTwoBytesToInt方法,我會得到一個非常小的數字。它應該是> 16000和不小於2000將Java整數轉換爲十六進制數並將其轉換爲int

我有兩種方法:

private static int convertTwoBytesToInt(byte[] a){ 
    String f1 = convertByteToHex(a[0]); 
    String f2 = convertByteToHex(a[1]); 
    return Integer.parseInt(f2+f1,RADIX16); 
} 

private static byte[] convertIntToTwoByte(int value){ 
    byte[] bytes = ByteBuffer.allocate(4).putInt(value).array(); 
    System.out.println("Check: "+Arrays.toString(bytes)); 
    byte[] result = new byte[2]; 
    //big to little endian: 
    result[0] = bytes[3]; 
    result[1] = bytes[2]; 
    return result; 
} 

我打電話給他們如下:

byte[] h = convertIntToTwoByte(16000); 
    System.out.println("AtS: "+Arrays.toString(h)); 
    System.out.println("tBtInt: "+convertTwoBytesToInt(h)); 

如果我使用值16000,沒有問題,但如果我使用16900,「convertTwoBytesToInt」的整數值是1060.

任何想法?

+0

爲什麼要以這樣的令人費解的方式這樣做,代替例如'INT B = A [0 ] << 8 |一個[1];'? – Kayaman

+0

@Kayaman - 我同意使用位操作,但由於符號擴展的原因,對於大於0x7f的字節值,您的建議不起作用。 –

+2

請在'convertByteToHex()中顯示代碼' – Bohemian

回答

0

根據您提供的示例,我猜測convertByteToHex(byte)在字節值小於0x10時轉換爲一位十六進制字符串。 16900是0x4204,1060是0x424。

您需要確保轉換零填充爲兩位數。

一個更簡單的方法是使用位操作以從字節構造int值:

private static int convertTwoBytesToInt(byte[] a) { 
    return ((a[1] & 0xff) << 8) | (a[0] & 0xff); 
} 
+0

是的,乍一看似乎很聰明,實現它就這樣,但現在......這不是很聰明。 – rXhalogene

+0

謝謝! :-)現在我必須檢查計算結果是否如我所願。 – rXhalogene

相關問題