Bitshifting in Java

Alexander picture Alexander · Oct 10, 2010 · Viewed 15.2k times · Source

I'm trying to understand how bit shift works. Can someone please explain the meaning of this line:

while ((n&1)==0) n >>= 1;

where n is an integer and give me an example of a n when the shift is executed.

Answer

Jon Hanna picture Jon Hanna · Oct 10, 2010

Breaking it down:

n & 1 will do a binary comparison between n, and 1 which is 00000000000000000000000000000001 in binary. As such, it will return 00000000000000000000000000000001 when n ends in a 1 (positive odd or negative even number) and 00000000000000000000000000000000 otherwise.

(n & 1) == 0 will hence be true if n is even (or negative odd) and false otherwise.

n >> = 1 is equivalent to n = n >> 1. As such it shifts all bits to the right, which is roughly equivalent to a division by two (rounding down).

If e.g. n started as 12 then in binary it would be 1100. After one loop it will be 110 (6), after another it will be 11 (3) and then the loop will stop.

If n is 0 then after the next loop it will still be 0, and the loop will be infinite.