Question

This may seem to you a very easy question but I am really stuck.

e = 16 >> 1 >> 2 % 2 == 8

This turns out to be true, but I don't get why. I know that I first do 2%2==0 but then what follows?

Was it helpful?

Solution

As you've said, the 2 % 2 gets evaluated first, leaving 16 >> 1 >> 0 == 8. Next comes the first >>, and when you right-shift 16 by one bit, you get 8. So the expression becomes 8 >> 0 == 8.

The next operator is the remaining >>, but now you're right-shifting by zero bits, which of course changes nothing; and the expression is 8 == 8. The last operation is ==, which of course returns true.

Note that when you right-shift an integer by one bit, it's the same as halving its value (and rounding down, if the original integer was odd). Whatever number of bits you right-shift by, you have to halve that many times. For example, 64 >> 3 is the same as 64 / 2 / 2 / 2 which is 8.

OTHER TIPS

== is (apart from the assignment =) the weakest binding operation, so you have 16 >> 1 >> 0 that is compared to 8, and that is true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top