Skip to main content

java int overflow 探究

· 2 min read

背景

遇到java int overflow的问题,想了解java的数字类型溢出是怎么处理的

jshell> 2147483647 + 1
$3 ==> -2147483648

jls确认规则

对于+操作,如果结果溢出会怎么处理?

数字类型有两部分:符号位数字位 , 对于溢出的数字,规则如下

数字有两部分:

  • 符号位 : 符号位和数学上的结果的符号相反
  • 数字位 : 2进制补码的低位

jls 文档

If an integer addition overflows, then the result is the low-order bits of the
mathematical sum as represented in some sufficiently large two's-complement
format. If overflow occurs, then the sign of the result is not the same as the sign of
the mathematical sum of the two operand values.

例子解释

2147483647 + 1 

这里面 21474836471 都是int 的字面量 , +操作之后会溢出,

10进制的值2147483647 对应的16进制是 7fffffff

扩展之后的值 2147483647 +1 对应的16进制是 ...000 10000000 然后 2147483647 +1 2的补码 ...111 011111111111111 ,

所以: 低位就是 11111111111 符号位: 和之前相反,所以是 1 所以 int 的每一位都是 1 , 所以是 -2147483648

相关阅读