[英]Java integer to hex and to int
我有問題,該方法無法按預期工作。 在大多數情況下,它可以工作。 但是,在某些情況下它不起作用。 我有一個包含一些值的字節數組。 以十六進制表示,例如:0x04 0x42(littleEndian)。 如果我使用convertTwoBytesToInt方法,則會得到一個非常小的數字。 它應該> 16000並且不小於2000。
我有兩種方法:
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。
任何想法?
根據您提供的示例,我的猜測是,當字節值小於0x10時, convertByteToHex(byte)
將轉換為一位十六進制字符串。 16900是0x4204,而1060是0x424。
您需要確保將轉換零填充到兩位數。
一種更簡單的方法是使用位操作從字節構造int
值:
private static int convertTwoBytesToInt(byte[] a) {
return ((a[1] & 0xff) << 8) | (a[0] & 0xff);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.