按位运算符的 2 次方取模?
- 2 的幂模如何仅适用于二进制数的低位 (
1011000111011010
)? - 这个数 mod 2 的 0 次方、2 的 4 次方是多少?
- 2 的幂与模运算符有什么关系?它是否拥有特殊属性?
- 有人能给我举个例子吗?
老师说“当你取某个东西的 2 次方时,你只需取它的低位”。我太害怕了,不敢问他的意思 =)
- How does mod of power of 2 work on only lower order bits of a binary number (
1011000111011010
)? - What is this number mod 2 to power 0, 2 to power 4?
- What does power of 2 have to do with the modulo operator? Does it hold a special property?
- Can someone give me an example?
The instructor says "When you take something mod to power of 2 you just take its lower order bits". I was too afraid to ask what he meant =)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(5)
萌化2024-11-26 23:53:46
他的意思是:
x modulo y = (x & (y − 1))
当 y 是 2 的幂时。
示例:
0110010110 (406) modulo
0001000000 (64) =
0000010110 (22)
^^^^<- ignore these bits
现在使用您的示例:
1011000111011010 (45530) modulo
0000000000000001 (2 power 0) =
0000000000000000 (0)
^^^^^^^^^^^^^^^^<- ignore these bits
1011000111011010 (45530) modulo
0000000000010000 (2 power 4) =
0000000000001010 (10)
^^^^^^^^^^^^<- ignore these bits
_蜘蛛2024-11-26 23:53:46
回答您的具体问题:
- mod 是余数运算符。如果应用于 0, 1, ... 中的一系列数字 x,则 x mod n 将是 0, 1, ..., n-1, 0, 1, ..., n-1,无穷无尽。当你的模数 n 是 2 的幂时,那么 x mod n 将以二进制形式从 0 计数到 n-1,再计数到 0,再计数到 n-1,依此类推;对于看起来像二进制 01xxxxx 的模 n,x mod n 将循环遍历每个低位 xxxxx。
- 二进制 1011000111011010 mod 1 为 0(mod 2^0 产生最后的零位;所有 mod 1 都为零)。二进制 1011000111011010 mod 二进制 10000 为 1010(mod 2^4 产生最后四位)。
- 二进制数除以 2 的幂特别有效,因为它只是移位和掩码;从数学上来说,这没什么特别的。
- 示例:参见问题 2 的回答。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
他的意思是,采用
number mod 2^n
相当于剥离n
最低阶(最右边)位之外的所有<代码>数字。例如,如果 n == 2,
那么换句话说,
number mod 4
与number & 相同。 00000011
(其中&
表示按位与)请注意,这在以 10 为基数的情况下完全相同:
number mod 10
给出最后一位数字以 10 为基数的数字,number mod 100
给出最后两位数字,等等。He meant that taking
number mod 2^n
is equivalent to stripping off all but then
lowest-order (right-most) bits ofnumber
.For example, if n == 2,
So in other words,
number mod 4
is the same asnumber & 00000011
(where&
means bitwise-and)Note that this works exactly the same in base-10:
number mod 10
gives you the last digit of the number in base-10,number mod 100
gives you the last two digits, etc.