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.