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.
The Java programming language also provides operators that perform bitwise and bit shift operations on integral types.
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.
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.
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.
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.
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