How does 0x80000000 equate to -2147483648 in java?

Taking the binary code 0x80000000 , we get

 1000 0000 0000 0000 0000 0000 0000 0000 

How does this relate to -2147483648 . I got this question with this program.

 class a { public static void main(String[] args) { int a = 0x80000000; System.out.printf("%x %d\n",a,a); } } meow@VikkyHacks :~/Arena/java$ java a 80000000 -2147483648 

EDIT I found out that 2 additions are used to represent negative numbers. When I try to equate this to the fact that 1 addition will be

 1 Comp. :: 0111 1111 1111 1111 1111 1111 1111 1111 2 Comp. :: 1000 0000 0000 0000 0000 0000 0000 0000 

which again makes no sense, How 0x80000000 equates to -2147483648

+7
java bits
source share
2 answers

This is what happens with a signed whole overflow basically.

It’s easier to take byte as an example. The byte value is always in the range of -128 to 127 (inclusive). Therefore, if you have a value of 127 (which is 0x7f), if you add 1, you get -128. This is also what you get if you dropped 128 (0x80) to byte :

 int x = 0x80; // 128 byte y = (byte) x; // -128 

Overflow (in the representations of the integer complement 2s) always goes from the highest expressed number to the lowest.

For unsigned types, the largest value overflows to 0 (which again is the lowest expressed number). This is harder to show in Java, since the only unsigned type is char :

 char x = (char) 0xffff; x++; System.out.println((int) x); // 0 
+14
source share

This is the case when there is overflow on the range of the data type. Here is an example that I can provide.

 int number = 0x80; // 0x80 is hexadecimal for 128 (decimal) byte castedNumber = (byte)(number); // On casting, there is overflow,as byte ranges from -128 to 127 (inclusive). System.out.println(castedNumber); //Output is -128. 
+1
source share

All Articles