int number = 3;
System.out.println(number & 1 << 2);
Given this snippet where I am performing bitwise AND to number and then left shifting by 2, Why is the result 0 and not 4 (0100)?
CodePudding user response:
Make it (number & 1) << 2 because what you are doing means shift 1 << 2 times and then & that with number.
CodePudding user response:
First, as multiple people have already mentioned, the & operator's precedence is smaller than <<'s. So your code would look like this: number & (1 << 2)
. Let's imagine your code looked like this instead: (number % 1) << 2
. Now, what does this do?
First, let's talk about the & operator. What does it do? In short, it will apply an AND gate to each bit of the two given numbers, recording the result of the gate in a new number:
a 0 0 1 1
b 1 1 1 0
result 0 0 1 0
An AND gate works in the following way: the result of this gate is 1 only when both inputs are 1, otherwise, the output of the gate is 0.
In your case, you have the following:
a ...number
b 0 0 0 0 0 0 0 1
Since each bit but the first one of b
is 0, the result will be all 0s, except for the first bit, which will be whatever the first bit of number
was (note that a & 1
is virtually equivalent to a % 2
).
The shift operator now will shift the only remaining bit to the left 2 bits, which will virtually multiply it by 4.
So, for example, if number
was 3, 3 & 1 would be 1 (the first bit of 3 is 1), and then 1 would be shifted over 2 bits, so the result would be 4.
In fact, the expression (number & 1) << 2
will produce only two values:
- 4, when the number is odd (its first bit is 1)
- 0, when the number is even (its first bit is 0)