例如,一个字节B中的位是10000010,如何将字符串分配给字符串str,即str = "10000010".
编辑
我从二进制文件中读取字节,并存储在字节数组中B.我用System.out.println(Integer.toBinaryString(B[i])).问题是
(a)当位以(最左边)1开始时,输出不正确,因为它转换B[i]为负的int值.
(b)如果位开头0,则输出忽略0,例如,假设B[0]为00000001,1而不是输出00000001
简单的场景:你有一个字节数组
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 javadoc说The 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 …