Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is 0x80000000 equated to -2147483648 in java?

Tags:

java

bit

bits

Taking the binary of 0x80000000 we get

1000 0000 0000 0000 0000 0000 0000 0000

How does this equate 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 learned that 2's complement is used to represent negative numbers. When I try to equate this with that 1's complement would be

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

which again does not make any sense, How does 0x80000000 equate to -2147483648

like image 280
vikkyhacks Avatar asked Sep 15 '13 15:09

vikkyhacks


People also ask

Can you use == for double?

Double equals ( == ) will perform a type conversion when comparing two things, and will handle NaN , -0 , and +0 specially to conform to IEEE 754 (so NaN != NaN , and -0 == +0 );

How do you know if two floating variables are equal?

If you just check if two floats subtracted from each other are less than E, but the difference comes out at -1, it will count it as being equal. We use the absolute value to ensure we can only get a value less than epsilon if the result is close to 0. Depending on your usage, the value of epsilon can vary.

Can we use == to compare double in Java?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.


2 Answers

This is what happens with signed integer overflow, basically.

It's simpler to take byte as an example. A byte value is always in the range -128 to 127 (inclusive). So if you have a value of 127 (which is 0x7f) if you add 1, you get -128. That's also what you get if you cast 128 (0x80) to byte:

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

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

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

char x = (char) 0xffff;
x++;
System.out.println((int) x); // 0
like image 126
Jon Skeet Avatar answered Oct 23 '22 13:10

Jon Skeet


This is the case when there is overflow, with respect to the range of a data type. Here is an example that I can share.

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.
like image 32
N. Pamnani Avatar answered Oct 23 '22 13:10

N. Pamnani