这两天在研究一个问题时,偶然的越到了 int 越界的问题,我很惊奇的发现,当一个 数 大于了 Integer.MAX_VALUE 时,用 System.out.println() 输出后,会得到一个负数。我很好奇这个负数是怎么来的,所以查了一下资料,了解了一下 Java 对于 int 越界的处理。在 Java 里,
对于 int 的越界处理十分的简单:当一个数超过了 Integer.MAX_VALUE 后,Java 就会从 Integer 的另一头从新开始,也就是从 Integer.MIN_VALUE 往回倒推。也就是 越界数能显示的结果 = Integer.MIN_VALUE + (越界数 – Integer.MAX_VALUE) – 1
代码示例如下:
public static void main(String[] args) {
BigDecimal magic = BigDecimal.valueOf(Math.pow(2, 32)).divide(new BigDecimal(“1.618”), 0, BigDecimal.ROUND_HALF_UP);
System.out.println(magic.intValue() + ” : “ + Integer.toBinaryString(magic.intValue()));
BigInteger bigInteger = new BigInteger(magic.toEngineeringString());
System.out.println(” ” + magic.toEngineeringString() + ” : “+ Long.toBinaryString(bigInteger.longValue()));
System.out.println(Integer.MIN_VALUE+ (magic.longValue() – Integer.MAX_VALUE) – 1);
}
// 结果
-1640475766 : 10011110001110000101001110001010
2654491530 : 10011110001110000101001110001010 -1640475766
参考资料
1.[How doeHow does Java handle integer underflows and overflows and how would you check for it?s Java handle integer underflows and overflows and how would you check for it?]
2.[Integer overflow]