根据我的理解,Integer
中的Java
类型是32位符号,最重要的位是有符号位。这就是Integer.MAX_VALUE
为2147483647
的原因,即:
1111111111111111111111111111111(1 repeated in 31 times).
所以我认为它实际上可以表示为:
01111111111111111111111111111111(a 0 followed by 1 repeated 31 times)
0
表示这是一个正整数。
然后是以下代码:
int test = -2147483647;
String converted = Integer.toBinaryString(test);
System.out.println(converted);
输出结果为:
10000000000000000000000000000001
为什么输出如上?对我来说,二进制流应该表示为-1
,因为最重要的位是1
意味着否定。
像这样:
int minusOne = -1;
String converted1 = Integer.toBinaryString(test);
System.out.println(converted1);
输出与上述相同:
10000000000000000000000000000001
任何解释?
答案 0 :(得分:2)
看下面的两个片段,你发现了问题:
int test = -2147483647;
String converted = Integer.toBinaryString(test);
System.out.println(converted);
int minusOne = -1;
String converted1 = Integer.toBinaryString(test);
System.out.println(converted1);
您正在打印相同的变量测试,这就是输出相同的原因。如果你打印输出“minusOne”,它将全部为1。
10000000000000000000000000000001 -> -2147483647 = Integer.MIN_VALUE + 1
11111111111111111111111111111111 -> -1
1111111111111111111111111111111 -> Integer.MAX_VALUE = 2147483647
10000000000000000000000000000000 -> Integer.MAX_VALUE + 1
10000000000000000000000000000000 -> Integer.MIN_VALUE = -2147483648
10000000000000000000000000000001 -> Integer.MIN_VALUE + 1
答案 1 :(得分:1)
除了@ dragon66之外,请注意这些是two's complement个数字。它们没有表示为符号,幅度。
在二进制补码表示中,一个通过反转所有位来否定一个数,然后加1.这样,只有一个0的表示。