When I use the Unsigned Right Shift (Logical Shift) operator in java, I get the same result as the normal right-shift operator would give. my code is:
byte b1 = -99; // 01100011
byte result = (byte) (b1 >>> 6);
String str = String.format("%8s", Integer.toBinaryString(result & 0xFF)).replace(' ', '0');
System.out.println("result: " result);
The preceding code produces the same output which is -13 with both of >>
and >>>
operators, what is the reason behind that and how to resolve it?
CodePudding user response:
First of all, byte
is a signed type in Java, and bit shifting (whether normal or with sign extension) is done in int
, so before performing the shift, the value of b1
is implicitly cast back to int (which preserves sign). (As an aside, the value -99 is not 01100011, it is 1001 1101 in byte
and 1111 1111 1111 1111 1111 1111 1001 1101 in int
).
With b >> 6
(or -99 >> 6
), the value is -2 (1111 1111 1111 1111 1111 1111 1111 1110), with b >>> 6
(or -99 >>> 6
) the value in int
is 67108862 (0000 0011 1111 1111 1111 1111 1111 1110). However, when you then cast to byte
, this last value becomes -2 as well (1111 1110).
What you need to do is make sure you get the unsigned value of the byte as the integer value before shifting:
byte result = (byte) ((b1 & 0xFF) >>> 6);
Which results in 2.