【问题标题】:Parsing Integer.MIN_VALUE from hex causes a NumberFormatException从十六进制解析 Integer.MIN_VALUE 会导致 NumberFormatException
【发布时间】:2016-12-01 18:01:13
【问题描述】:

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

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

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

下面是一个运行示例:

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

【问题讨论】:

    标签: java integer number-formatting numberformatexception


    【解决方案1】:

    toHexString 方法返回数字的无符号字符串表示。

    另见 SOJava negative int to hex and back fails

    【讨论】:

      猜你喜欢
      • 2012-07-07
      • 1970-01-01
      • 2022-11-16
      • 2010-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      相关资源
      最近更新 更多