呵呵,好奇。我认为这是一个“故意的错误”,可以这么说。
根本原因是 Integer 类的编写方式。基本上, parseInt 针对正数进行了“优化”。当它解析字符串时,它会累积地构建结果,但会被否定。然后它翻转最终结果的符号。
例子:
66 = 0x42
解析为:
4*(-1) = -4
-4 * 16 = -64 (hex 4 parsed)
-64 - 2 = -66 (hex 2 parsed)
return -66 * (-1) = 66
现在,让我们看一下您的示例 FFFF8000
16*(-1) = -16 (first F parsed)
-16*16 = -256
-256 - 16 = -272 (second F parsed)
-272 * 16 = -4352
-4352 - 16 = -4368 (third F parsed)
-4352 * 16 = -69888
-69888 - 16 = -69904 (forth F parsed)
-69904 * 16 = -1118464
-1118464 - 8 = -1118472 (8 parsed)
-1118464 * 16 = -17895552
-17895552 - 0 = -17895552 (first 0 parsed)
Here it blows up since -17895552 < -Integer.MAX_VALUE / 16 (-134217728).
Attempting to execute the next logical step in the chain (-17895552 * 16)
would cause an integer overflow error.
编辑(添加):为了使 parseInt() 能够“一致地”为 -Integer.MAX_VALUE <= n <= Integer.MAX_VALUE 工作,他们必须在达到 -Integer.MAX_VALUE 时实现逻辑“旋转”累积结果,从整数范围的最大值开始并从那里继续向下。他们为什么不这样做,必须先询问 Josh Bloch 或最初实施它的人。这可能只是一个优化。
然而,
Hex=Integer.toHexString(Integer.MAX_VALUE);
System.out.println(Hex);
System.out.println(Integer.parseInt(Hex.toUpperCase(), 16));
工作得很好,正是因为这个原因。在 Integer 的源代码中,您可以找到此评论。
// Accumulating negatively avoids surprises near MAX_VALUE