为什么java方法Integer.toBinaryString(-128)输出七位数?

sni*_*10m 5 java binary byte twos-complement

简单的场景:你有一个字节数组

byte[] message = { 1, 2, 3 };

要以二进制打印出来,您可以使用以下代码:

for (byte b : message) {
    System.out.println(Integer.toBinaryString(0x100 + b).substring(1));
}
Run Code Online (Sandbox Code Playgroud)

(从这个堆栈溢出线程获得该代码)

得到这个输出:

00000001
00000010
00000011
Run Code Online (Sandbox Code Playgroud)



但如果你最后标记-128 ......

byte[] message = { 1, 2, 3, -128 };

00000001
00000010
00000011
0000000
Run Code Online (Sandbox Code Playgroud)

哇!七位二进制数?我觉得这与两个补码有关,但我试着读的越多,我就越困惑.我期待着10000000出现在第四行而不是......

任何人都可以解释为什么Integer.toBinaryString-128是相对简单的术语七位数?


Ye olde javadocThe unsigned integer value is the argument plus 2^32 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s. 但是就像我说的那样......只是让我困惑.



整个事情的背景是我正在尝试编写java中的一些SHA函数.不要问我为什么,我甚至不知道......我只是好奇/挑战自己/沮丧自己:)

根据文档,在SHA-256函数中使用的消息的填充(使其为位长的512的倍数)是以下的串联:

  1. 原始消息
  2. 1点点
  3. 0 位到最后64位
  4. 原始消息长度为64位值

由于我的消息很可能是ASCII 8位代码,我只需要标记10000000为#2 ...然后我可以计算0要添加的BYTES 的数量,我不应该计划消息不是8的倍数.问题是这样做10000000.

fab*_*ian 7

(-128 + 0x100) =
(256 - 128) = 128 = 
0b10000000

Integer.toBinaryString(0b10000000) = "10000000"

"10000000".substring(1) = "0000000"
Run Code Online (Sandbox Code Playgroud)