Denys_newbie
Denys_newbie

Reputation: 1160

Confused with byte convertion to int

How a byte value b when uses as int in the Integer.toBinaryString() have a binary value much more than byte type can contain? I thought s1 should be in range [0, 11111111]. And how this bitwise operator (b & 0B11111111) changes the situation? It seems that it changes nothing because 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
    }
}

Upvotes: 2

Views: 82

Answers (2)

khelwood
khelwood

Reputation: 59112

For a byte, -115 dec is 10001101 bin. If you promote that byte to an int with the same value (which is what happens when you call Integer.toBinaryString(b)), -115 dec is 11111111111111111111111110001101 bin.

Whereas if you take your int -115 and & it with 0B11111111, you get the last eight bits of 11111111111111111111111110001101, which is 10001101 bin, 141 dec.

For a byte 10001101 bin is -115, because the largest bit is negative. For an int 10001101 bin is 141 dec, and the largest bit isn't set because you're only using the smallest 8 bits of a 32 bit integer.

Upvotes: 1

Sweeper
Sweeper

Reputation: 271390

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 context. The byte is converted to int first, then passed to Integer.toBinaryString.

What's -115 represented in 32 bit two's complement (representation of an int)? Well,

1111 1111 1111 1111 1111 1111 1000 1101

That is the binary string you got.


The & 0B11111111 here actually does something. The & operator causes the byte to undergo numeric promotion, converting it to an int. Now we have -115 as a 32-bit int, with all those extra leading 1s that we don't want. The bit mask then gets applied, resulting in the int 141 (1000 1101). We then convert this int to a binary string.

Upvotes: 3

Related Questions