Java 整数到十六进制和整数

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);
}