Integer min/max value peculiar overflow behavior
java, jvm, scala
Solution
`Integer.MIN_VALUE= -2147483648`. Have a look at bit calculation of `2 * -2147483648`
Integer.MIN_VALUE*2 = Integer.MIN_VALUE+Integer.MIN_VALUE
-2147483648= 10000000 00000000 00000000 00000000 ->32 bit
+10000000 00000000 00000000 00000000
_________________________________________________________________
2* -2147483648= 1 00000000 00000000 00000000 00000000 Result is 0
|
This bit will be omitted due to limitation of 32 bit
`Integer.MAX_VALUE=2147483647`, Have a look at bit calculation of `2 * 2147483647`
Integer.MAX_VALUE*2 = Integer.MAX_VALUE+Integer.MAX_VALUE
2147483647= 01111111 11111111 11111111 11111111 ->32 bit
+01111111 11111111 11111111 11111111
_________________________________________________________________
2* 2147483647= 11111111 11111111 11111111 11111110 Result is -2
Problem
Why is `Integer.MIN_VALUE * 2` equal to `0`? And `Integer.MAX_VALUE * 2` equal to `-2`? Let me explain myself better: I know it overflows, but why does it get these specific results?