Consider the following code:
int a=10, b=5;
int c=a>>2+b>>2;
System.out.println(c);
When run, the (surprising) output is 0.
Why is it so?
Taking Java's operator precedence (notably that + has higher precedence than >>) and associativity rules into account, the expression is equivalent to
(a >> (2 + b)) >> 2
or
(10 >> (2 + 5)) >> 2
which is zero.
If you need the shifts to happen before the addition, parenthesise them:
(a >> 2) + (b >> 2)
Because it's like writing (Operator Precedence):
(a >> (2 + 5)) >> 2
Which is like writing:
(10 >> 7) >> 2
Which is 0. Why?
Think about the binary representation of 10, assuming 8-bit:
00001010
Now, shift it right by 7 and you'll get 0. Shift it right by 2, you'll still get 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With