I am experiencing some weird unsigned right shift operation producing wrong results when trying to perform them on hard-coded and not hard-coded data on Java 8.
I am trying to perform a unsigned right shift on a signed byte 0xBF
. If I simply assigned the signed byte to a variable and then use the variable to perform an unsigned right shift operation, I end up getting 0xDF
. If I hard-code the 0xBF into the unsigned right shift operation, I get 0x5F
.
byte originalByte = (byte) 0xBF;
System.out.println("Original Data: " + toHexString(new byte[]{originalByte}));
byte rotatedByte = (byte) (originalByte >>> 1);
System.out.println("Rotated Data: " + toHexString(new byte[]{rotatedByte}));
byte signRemoved = (byte) (0xBF >>> 1);
System.out.println("Sign Removed Data: " + toHexString(new byte[]{signRemoved}));
The output from the above Java call.
Original Data: BF
Rotated Data: DF
Sign Removed Data: 5F
How should I solve the above problem ?