Question

Code:

System.out.println((byte)0b10000000 >> 6);
System.out.println(0b10000000 >> 6);

Output:

-2
2

I know that passing in an uncasted byte will turn it into an Integer (second line).
It still gives the expected answer of 2, aka 0b10.

However, casting it as an Byte (first line) returns -2.

I am confused why.

Was it helpful?

Solution

Bytes are 8 bit signed integers, so when you cast the first binary number to byte, the first bit is interpreted as the sign, therefore it's interpreted as -127.

You can solve this by using System.out.println((byte)(0b10000000 >> 6)); (casting after the shift).

I know that passing in an uncasted byte...

Erm, 0b... does not mean "byte;" it means "binary." You are not passing in an uncasted byte at all. (Your binary literal does fit in a byte, but it's interpreted as an int.)

OTHER TIPS

The shift operator >> keeps the sign bit.

The value of n >> s is n right-shifted s bit positions with sign-extension.

So the byte value

1000 0000 

promoted to an int, as required by the Java Language Specification

Unary numeric promotion (§5.6.1) is performed on each operand separately.

gives

1111 1111 1111 1111 1111 1111 1000 0000

because widening conversion from byte to int

A widening conversion of a signed integer value to an integral type T simply sign-extends the two's-complement representation of the integer value to fill the wider format.

and shifted by 6 becomes

1111 1111 1111 1111 1111 1111 1111 1110

which is the integer value -2.

In the case of

System.out.println(0b10000000 >> 6);

The literal is actually an int, ie.

0000 0000 0000 0000 0000 0000 1000 0000 

so shifting by 6 to the right becomes

0000 0000 0000 0000 0000 0000 000 0010 

with a value of 2.

Here's the steps of each shift to make it clear what's happening

byte (signed with MSB=1)

10000000(-128)
11000000(-64)
11100000(-32)
11110000(-16)
11111000(-8)
11111100(-4)
11111110(-2)

integer (signed with MSB=0)

0000000010000000(128)
0000000001000000(64)
0000000000100000(32)
0000000000010000(16)
0000000000001000(8)
0000000000000100(4)
0000000000000010(2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top