Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

bits - How is 0x80000000 equated to -2147483648 in java?

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
",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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...