在 java 中从十六进制转换为整数,反之亦然

Convert from hex to int and vice versa in java

我有下一个从十六进制转换为 int 的方法:

public static byte[] convertsHexStringToByteArray2(String hexString) {
    int hexLength = hexString.length() / 2;
    byte[] bytes = new byte[hexLength];
    for (int i = 0; i < hexLength; i++) {
        int hex = Integer.parseInt(hexString.substring(2 * i, 2 * i + 2), 16);
        bytes[i] = (byte) hex;
    }

    return bytes;
}

当我将它用于“80”十六进制字符串时,我感到奇怪,不是预期的结果:

public static void main(String[] args) {
    System.out.println(Arrays.toString(convertsHexStringToByteArray2("80"))); // gives -128
    System.out.println(Integer.toHexString(-128));
    System.out.println(Integer.toHexString(128));
}

输出:

[-128]
ffffff80
80

我预计“80”将是 128。我的方法有什么问题吗?

I have next method for converting to int from hex

您发布的方法将十六进制字符串转换为字节数组,而不是 int。这就是为什么它弄乱了它的标志。

从十六进制转换为整数 很容易:

Integer.parseInt("80", 16)
 ==> 128

但是如果你想通过强制转换获得一个字节数组用于进一步处理:

(byte) Integer.parseInt("80", 16)
 ==> -128

它“改变”了它的符号。有关基元和有符号变量类型的更多信息,请查看 Primitive Data Types,其中显示:

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

只需增加要转换的值即可轻松反转符号:

(byte) Integer.parseInt("80", 16) & 0xFF
 ==> 128

这将为您提供一个具有您期望的值的字节。从技术上讲,该结果不正确,如果您想再次返回一个 int 或 hex 字符串,则必须再次切换符号。如果你只想在十六进制和十进制之间转换,我建议你不要使用字节数组。

Java中的一个字节存储-128到127之间的数字。80在十六进制中是整数128,它太大而不能存储在一个字节中。所以,价值环绕。使用不同的类型来存储您的值(例如短)。