Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitshifting in Java

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.

like image 720
Alexander Avatar asked Oct 10 '10 17:10

Alexander


People also ask

Can you Bitshift in Java?

The Java programming language also provides operators that perform bitwise and bit shift operations on integral types.

What is >> and << in Java?

Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.

What is the use of >>> in Java?

In Java, the operator '>>' is signed right shift operator. All integers are signed in Java, and it is fine to use >> for negative numbers. The operator '>>' uses the sign bit (leftmost bit) to fill the trailing positions after the shift.

What does |= mean in Java?

The bitwise OR assignment operator ( |= ) uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable.


1 Answers

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.

like image 60
Jon Hanna Avatar answered Oct 18 '22 17:10

Jon Hanna