混淆字节转换为 int

Confused with byte convertion to int

在 Integer.toBinaryString() 中用作 int 时,byteb 如何具有比 byte 类型可以包含的二进制值更多的二进制值?我认为 s1 应该在 [0, 11111111] 范围内。这个按位运算符 (b & 0B11111111) 如何改变这种情况?它似乎没有任何改变,因为 0 & 1 = 0 and 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 accepts an int, so you are actually converting the int -115 to a binary string. As far as Integer.toBinaryString is concerned, the number you passed to it is always an int. The fact that you are able to pass a byte is because there is a conversion from byte to int in an invocation contextbyte首先转换int然后传递给Integer.toBinaryString

-115 在 32 位二进制补码中表示什么(int 的表示)?嗯,

1111 1111 1111 1111 1111 1111 1000 1101

这就是你得到的二进制字符串。


这里的& 0B11111111实际上做了一些事情& 运算符使 byte 经历 numeric promotion,将其转换为 int。现在我们有 -115 作为 32 位 int,所有那些我们不想要的额外前导 1。然后应用位掩码,导致 int 141 (1000 1101)。然后我们将 this int 转换为二进制字符串。

对于一个字节,-115 dec 是 10001101 bin。如果将该字节提升为具有相同值的 int(当您调用 Integer.toBinaryString(b) 时会发生这种情况),-115 dec 是 11111111111111111111111110001101 bin.

而如果你把你的 int -115 和 & 它与 0B11111111 一起,你会得到 11111111111111111111111110001101 的最后八位,即 10001101 bin, 141十二月

对于一个字节10001101bin是-115,因为最大的位是负数。 对于 int 10001101 bin 是 141 dec,并且未设置最大位,因为您仅使用 32 位整数的最小 8 位。