从十六进制解析 Integer.MIN_VALUE 导致 NumberFormatException

Parsing Integer.MIN_VALUE from hex causes a NumberFormatException

我尝试将 Integer.MIN_VALUE 从十六进制解析为整数,但我得到了 NumberFormatException。当我向字符串添加减号时,它正在工作。

  1. 这是一个错误还是我误解了什么。从我的角度来看,编码和解码应该是双射的。但好像不是。

  2. 我必须解码“0x80000000”。我该怎么做?我可以捕获异常并将减号添加到 String 并重试。但这对我来说似乎不干净。

这里有一个运行例子:

public static void main(String[] args) {
    int i1 = Integer.MIN_VALUE; //0x80000000
    String s1 = Integer.toHexString(i1);
    String s2 = "-" + s1;

    System.out.println(String.format("Out1: %1$d | %1$h == %2$s <> %3$s", i1 , s1, s2));
    // Out1: -2147483648 | 80000000 == 80000000 <> -80000000

    // this should work, but does not
    try {
        int s1_parsed = Integer.parseInt(s1, 16);
        System.out.println(String.format("Out2: %1$d | %1$h, %2$d | %2$h", i1, s1_parsed));
    } catch (NumberFormatException ex) {
        ex.printStackTrace();
    }

    // this is working, but I do not know why
    try {
        int s2_parsed = Integer.parseInt(s2, 16);
        System.out.println(String.format("Out3: %1$d | %1$h == %2$d | %2$h", i1, s2_parsed));
        // Out3: -2147483648 | 80000000 == -2147483648 | 80000000
    } catch (NumberFormatException ex) {
        ex.printStackTrace();
    }
}

toHexString 方法returns 数字的无符号字符串表示形式。

另见 SO Java negative int to hex and back fails