[英]Unable to understand Bitwise & operator in java
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)?给定这个片段,我对数字执行按位与,然后左移 2,为什么结果是 0 而不是 4(0100)?
让它(number & 1) << 2因为你正在做的意味着移动 1 << 2 次,然后 & 与数字。
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)
.所以你的代码看起来像这样:
number & (1 << 2)
。 Let's imagine your code looked like this instead: (number % 1) << 2
.让我们想象一下您的代码看起来像这样:
(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.与门的工作方式如下:只有当两个输入都为 1 时,此门的结果才为 1,否则,门的输出为 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
).由于除了
b
的第一个之外的每一位都是 0,因此结果将全为 0,除了第一位,这将是number
的第一位(注意a & 1
实际上等同于a % 2
)。
The shift operator now will shift the only remaining bit to the left 2 bits, which will virtually multiply it by 4.移位运算符现在会将唯一剩余的位向左移动 2 位,这实际上将其乘以 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.因此,例如,如果
number
为 3,则 3 & 1 将为 1(3 的第一位是 1),然后 1 将移动 2 位,因此结果将为 4。
In fact, the expression (number & 1) << 2
will produce only two values:事实上,表达式
(number & 1) << 2
只会产生两个值:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.