2015-06-03 67 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