Originally posted by srijan sharma:
hi all,
there is a small piece of code
byte b = -4;
b=(byte)(b>>>2)
i fail to undestand that can shift operators be applied on byte type and how the output will come???
thanks in advance
srijan
Hello Srijan,
Let see if I can make sense of this. Here what we all learn:
<< - means shifting left, filling with zero from the right.<br /> >> - means shifting right, propagating the sign bit from the left.
>>> - means shifting right, filling with zero from the left.
With that, we expect a >>> unsigned-right-shift operator would change negative sign into positive. And -4 >>> 2 would be equal to 1.
However if -4 is a value of a byte or a short, the answer would be -1 ... What happens? The sign is still negative!
Here is what I think happens, please correct me if I am wrong. First, b will be widen to an int. Therefore -4 has the following form:
11111111111111111111111111111100
Now b>>>2 will yield this
00111111111111111111111111111111
Then you cast it into a byte, so this is what you get
11111111
And that is -1
Now try this code:
short s = -4;
s >>>= 2;
Well, again the answer is -1 because if you take the last 16 bits of the following
pattern 00111111111111111111111111111111
you will get
1111111111111111
and that is a -1 too.
However with this code:
int i = -4;
i >>>= 2;
you will get 1073741823
and that is 00111111111111111111111111111111
Can you guess the answers of the following code for b,s, and i?
byte b = -4;
short s = -4;
int i = -4;
b >>>= 30; s >>>= 30; i >>>= 30;
Your guesses are right; They all yield 3. Well they all change sign and that is the magic.
What do you think? Does that explain it?
Lam
[This message has been edited by Lam Thai (edited April 20, 2001).]