我遇到問題,該方法無法按預期工作。在大多數情況下,它的作品但是有一種情況不起作用。 我有一個包含一些值的字節數組。在十六進制例如: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.
任何想法?
爲什麼要以這樣的令人費解的方式這樣做,代替例如'INT B = A [0 ] << 8 |一個[1];'? – Kayaman
@Kayaman - 我同意使用位操作,但由於符號擴展的原因,對於大於0x7f的字節值,您的建議不起作用。 –
請在'convertByteToHex()中顯示代碼' – Bohemian