Just got a doubt when working on the >>> operators with negative number. Having read that ">>> operator works the same way as >> operator except it does NOT retain the sign bit and instead it fills it with zeroes".
When i try with an example for int datatype it works. But it does not seem to work with byte.
See this example:
The work out is :
the decimal equivalent of -121 is : 1000 0111 -121 >>> 2 is : 1000 0111 >>> 2 -> 0010 0001 which should be 32+1 = 33.
This should give the output as +33. But it gives the output as "-31".
What am i missing here? It would be great if any one could help here!
The << and >> operators work in exactly the same way as the >>> operator. The only difference between >>> and >> is that >>> shifts zeroes in on the left side, while >> copies the leftmost bit of the original value (sign extension). When doing >>> or >> on a byte and then casting the result back to a byte, the result will be the same, because the leftmost bits of the intermediate int are thrown away.
For the exact details, see section 15.19 of the Java Language Specification. According to the specification, the value is first converted to either an int or a long using unary numeric promotion. So I don't think there is a way to shift a byte directly. You could ofcourse use the & (bitwise AND) operator to mask off the top bits after the shift:
byte y = (byte) ((x >>> 2) & 0x3f); [ January 04, 2008: Message edited by: Jesper Young ]