0x80000000 在java中如何等同于-2147483648?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18813875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:17:50  来源:igfitidea点击:

How is 0x80000000 equated to -2147483648 in java?

javabits

提问by vikkyhacks

Taking the binary of 0x80000000we get

取二进制0x80000000我们得到

1000 0000 0000 0000 0000 0000 0000 0000

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

这如何等同于-2147483648. 我在这个程序中遇到了这个问题。

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

EDITI learned that 2's complement is used to represent negative numbers. When I try to equate this with that 1's complement would be

编辑我了解到 2 的补码用于表示负数。当我试图将其与 1 的补码相提并论时

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 0x80000000equate to -2147483648

这又没有任何意义,如何0x80000000等同于-2147483648

采纳答案by Jon Skeet

This is what happens with signed integer overflow, basically.

基本上,这就是有符号整数溢出会发生的情况。

It's simpler to take byteas an example. A bytevalue 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:

byte举个例子就更简单了。甲byte值始终是在-128到127(含)的范围内。所以如果你有一个值127(即 0x7f),如果你加 1,你会得到 -128。如果您将 128 (0x80) 转换为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.

溢出(在 2s 补码整数表示中)总是从最高的可表达数到最低的数。

For unsignedtypes, 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:

对于无符号类型,最高值溢出到 0(这也是最低的可表示数)。这在 Java 中更难显示,因为唯一的无符号类型是char

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

回答by N. Pamnani

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.