Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

c - Mod of power 2 on bitwise operators?

  1. How does mod of power of 2 work on only lower order bits of a binary number (1011000111011010)?
  2. What is this number mod 2 to power 0, 2 to power 4?
  3. What does power of 2 have to do with the modulo operator? Does it hold a special property?
  4. 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 =)

question from:https://stackoverflow.com/questions/6670715/mod-of-power-2-on-bitwise-operators

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

He meant that taking number mod 2^n is equivalent to stripping off all but the n lowest-order (right-most) bits of number.

For example, if n == 2,

number      number mod 4
00000001      00000001
00000010      00000010
00000011      00000011
00000100      00000000
00000101      00000001
00000110      00000010
00000111      00000011
00001000      00000000
00001001      00000001
etc.

So in other words, number mod 4 is the same as number & 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...