[英]Java Integer to Binary confusion
According to my comprehension, Integer
type in Java
is 32-bit-signed, the most significant bit is the signed bit. 根据我的理解, Java
Integer
类型是32位带符号的,最高有效位是带符号的位。 This is why Integer.MAX_VALUE
is 2147483647
, which is: 这就是为什么Integer.MAX_VALUE
是2147483647
,这是:
1111111111111111111111111111111(1 repeated in 31 times).
So I assume that it actually can be represented as: 因此,我认为它实际上可以表示为:
01111111111111111111111111111111(a 0 followed by 1 repeated 31 times)
The 0
means this is a positive integer. 0
表示这是一个正整数。
Then for the following codes: 然后输入以下代码:
int test = -2147483647;
String converted = Integer.toBinaryString(test);
System.out.println(converted);
The output is: 输出为:
10000000000000000000000000000001
Why the output is like above? 为什么输出如上? For me, the binary stream should be represented as -1
, since the most significant bit is 1
means negative. 对我而言,二进制流应表示为-1
,因为最高有效位为1
表示负数。
Like this: 像这样:
int minusOne = -1;
String converted1 = Integer.toBinaryString(test);
System.out.println(converted1);
The output is the same as above: 输出与上面相同:
10000000000000000000000000000001
Any explanation? 有什么解释吗?
Look at the folowing two snippets, did you find the problem: 查看以下两个代码片段,您是否发现了问题:
int test = -2147483647;
String converted = Integer.toBinaryString(test);
System.out.println(converted);
int minusOne = -1;
String converted1 = Integer.toBinaryString(test);
System.out.println(converted1);
You are printing out the same variable test, that's why the output is the same. 您正在打印相同的变量测试,这就是输出相同的原因。 If you printout "minusOne" it would be all 1's. 如果打印出“ 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
In addition to @dragon66's point, be aware that these are two's complement numbers. 除了@ dragon66的要点外,请注意,这些是二进制补码。 They are not represented as sign, magnitude. 它们未表示为符号,大小。
In two's complement representation, one negates a number by inverting all the bits, then adding 1. This way, there's only one representation of 0. 在二进制补码表示中,一个运算符通过反转所有位然后加1来取反数字。这样,只有一个表示0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.