Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer min/max value peculiar overflow behavior

Tags:

java

jvm

scala

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?

like image 824
NightRa Avatar asked Nov 29 '13 09:11

NightRa


1 Answers

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
like image 66
Masudul Avatar answered Oct 02 '22 09:10

Masudul