Why does a negative value of Integer.MIN_VALUE give the same value?

Consider the java code below.

Integer value = Integer.MIN_VALUE; System.out.println(value); value = -value; System.out.println(value); 

Exit

 -2147483648 -2147483648 

How does a negative value of an Integer.MIN_VALUE value give the same value?

However, the result cannot be 2147483648 , because the maximum Integer value in java is 2147483647 .

But want to know why -2147483648 ? What bitwise operations occur domestically?

+7
java operators bitwise-operators ones-complement
source share
2 answers

What bit operations happen inside?

Java uses two additions to indicate signed numbers. Therefore, changing the sign operation consists of two steps:

  • Invert bits of the original value and
  • Appendix 1 to the result.

2147483648 shown below:

 10000000000000000000000000000000 

Inverting creates

 01111111111111111111111111111111 

Appendix 1 returns it again, i.e.

 10000000000000000000000000000000 

due to integer overflow.

+10
source share

When you negate -2147483648 , it resolves to 2147483648 , which exceeds Integer.MAX_VALUE with 1 . Then the value overflows to Integer.MIN_VALUE again.

From JLS :

Integral types are bytes, short, int, and long, whose values ​​are 8-bit, 16-bit, 32-bit, and 64-bit signed two padding characters.

So, any unary operation performed on an integer will actually be applied to two additional representations of the number. When Integer.MAX_VALUE reached, it will consist of the first bits 0 and 31 1 . Adding 1 would make this number with a leading 1 and 31 trailing 0 s, which is actually two additional representations of Integer.MIN_VALUE .

+12
source share

All Articles