在 Integer.toBinaryString() 中用作 int
时,byte
值 b
的二进制值如何远大于 byte
类型可以包含什么?我认为 s1 应该在 [0, 11111111] 范围内。这个按位运算符(b & 0B11111111
)如何改变这种情况?看起来它没有改变任何东西,因为 0 & 1 = 0 和 1 & 1 = 1
public class Test
{
public static void main(String[] args)
{
byte b = (byte) -115;
String s1 = Integer.toBinaryString(b);
String s2 = Integer.toBinaryString(b & 0B11111111);
System.out.println(s1); // 11111111111111111111111110001101
System.out.println(s2); // 10001101
}
}
最佳答案
Integer.toBinaryString
接受 int
,因此您实际上是将 int -115
转换为二进制字符串。就 Integer.toBinaryString
而言,您传递给它的数字始终是 int
。事实上,您能够传递字节
是因为有一个conversion from byte
to int
在 invocation context 。 byte
首先转换为int
,然后传递给Integer.toBinaryString
。
用 32 位二进制补码表示的 -115
是什么(int
的表示形式)?嗯,
1111 1111 1111 1111 1111 1111 1000 1101
这就是你得到的二进制字符串。
这里的& 0B11111111
实际上做了一些事情。 &
运算符导致 byte
经历 numeric promotion ,将其转换为 int
。现在我们有 -115
作为 32 位 int
,以及所有我们不需要的额外前导 1。然后应用位掩码,得到 int
141 (1000 1101)。然后我们将 this int
转换为二进制字符串。
关于java - 与字节转换为 int 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65837892/