-1

I am trying to get the first 4 bits of a byte number, as another number. So I wrote something like this:

byte b = (byte)0xF4;
byte b1 = b >>> 4;

Why is the second statement not allowed in Java?

Edit:

I made changes as written in answer, it is leads to answer 0xFF, but 0x0F was expected;

Then I tried to present values in binary and noticed:

System.out.println(Integer.toBinaryString(0xF1));
System.out.println(Integer.toBinaryString((byte)0xF1));
System.out.println(Integer.toBinaryString((byte)0xF1 >>> 4));
System.out.println(Integer.toBinaryString(0xF1 >>> 4));

Output:

11110001
11111111111111111111111111110001
11111111111111111111111111111111
1111

It is simply that 0xF1 and (byte)0xF1 are different numbers. And operator (>>>) in one case add zeroes and units in other.

So I need to assign 0xF4 to byte b (which is signed), like it is unsigned byte, then make bit shift and receive 0x0F as result.

1 Answers1

2

It's because >>> (and other binary operators) promotes the operands to at least int (as described in JLS Sec 15.19). In this case, they are promoted to exactly int, and the result is then int, since the promoted type of the left-hand operand is int.

You need to cast explicitly back to byte:

byte b1 = (byte) (b >>> 4);

or use a compound assignment (which implicitly casts for you):

byte b1 = b; b >>>= 4;
Andy Turner
  • 137,514
  • 11
  • 162
  • 243