0x80000000在Java中如何等于-2147483648? [英] How is 0x80000000 equated to -2147483648 in java?
问题描述
采用0x80000000
的二进制代码,我们得到
Taking the binary of 0x80000000
we get
1000 0000 0000 0000 0000 0000 0000 0000
这等同于-2147483648
.我在这个程序中遇到了这个问题.
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
编辑我了解到2的补码用于表示负数.当我尝试将其与1的补码等同时
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
这又没有任何意义,0x80000000
等同于-2147483648
which again does not make any sense, How does 0x80000000
equate to -2147483648
推荐答案
有符号整数溢出会发生这种情况,基本上.
以byte
为例更简单. byte
值始终在-128到127(含)范围内.因此,如果将值加1,则值为127
(即0x7f),则得到-128.这也是将128(0x80)投射到byte
时得到的结果:
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
溢出(以2s补码整数表示)总是从最高可表达数字到最低可表达数字.
Overflow (in 2s complement integer representations) always goes from the highest expressible number to the lowest one.
对于 unsigned 类型,最大值溢出到0(这也是最低的可表示数字).这在Java中很难显示,因为唯一的无符号类型是char
:
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
这篇关于0x80000000在Java中如何等于-2147483648?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!