为什么 ( x & 3 ) 与 ( x mod 4 ) 相同?
我找到了一些示例源代码,其中作者似乎使用按位 &
运算符而不是 %
运算符。然而,当我尝试 x & 4 它不会产生与 x % 5
相同的值。
I found some example source code where the author seems to use bitwise &
operator instead of %
operator. However when I tried x & 4
it doesn't produce the same value as x % 5
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这仅适用于 2 的幂。
一般来说:
相当于:
另请注意,这可能仅适用于
x >= 0
,具体取决于您对MOD
的定义对于x < 0 。
要理解为什么会这样,请考虑一下 MOD 到底是什么 - 它只是执行整数除法后的余数。在除以 2^n 的情况下,我们实际上只是将二进制值右移 n 位并丢弃移出的任何低位,例如,对于 8 位二进制数,
如果我们除以 4 = 2^2然后我们右移 2 位:
整数除法的结果是余数 (
g h
) 被丢弃。如果我们想知道余数,那么我们可以通过应用
0 0 0 0 0 0 1 1
掩码来提取位g h
:请注意,has 的值为 3 ,一般情况下只是 2^n - 1。
让我们用一些实数来尝试一下。假设我们要计算 42 / 4 并获得商和余数:
为了获得商,我们将右移 2 位:
因此 42/4 = 10 余数 2。
This only works for powers of 2.
In general:
is equivalent to:
Note also that this may be true only for
x >= 0
, depending on your definition ofMOD
forx < 0
.To understand why this works, consider what MOD really is - it's just the remainder after performing integer division. In the case of a division by 2^n, we are effectively just shifting a binary value right by n bits and discarding any low order bits that get shifted out, e.g. for an 8 bit binary number
if we divide by 4 = 2^2 then we shift right by 2 bits:
The remainder (
g h
) has been thrown away as a result of the integer division.If we wanted to know the remainder then we could just extract the bits
g h
by applying a mask of0 0 0 0 0 0 1 1
:Note that the has has value 3, which in the general case is just 2^n - 1.
Let's try this with some real numbers. Suppose we want to calculate 42 / 4 and get both the quotient and the remainder:
To get the quotient we shift right by 2 bits:
So 42/4 = 10 remainder 2.
答案很简单,尝试用二进制来思考。
... 等等。
这与提醒具有相同的结果(% 是形式上的余数,而不是模数)。
它仅适用于 2 的幂且仅适用于零和正数。
The answer quite simple, try to think in binary.
... and so on.
This have the same result as reminder (% is remainder, formally, not modulus).
It works only with powers of 2 and only for zero and positive numbers.