- 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 =)
Answering your specific questions:
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.Modulo in general returns the remainder of a value after division. So
x mod 4
, for example, returns 0, 1, 2 or 3 depending on x. These possible values can be represented using two bits in binary (00, 01, 10, 11) - another way to dox mod 4
is to simply set all the bits to zero in x except the last two ones.Example:
Consider when you take a number modulo 10. If you do that, you just get the last digit of the number.
Likewise if you take a number modulo 100, you just get the last two digits.
So you can get the modulo of a power of two by looking at its last digits in binary. That's the same as doing a bitwise and.
What he means is that :
When y is a power of 2.
Example:
Using your example now :