Mod of power 2 on bitwise operators?
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 400000001 0000000100000010 0000001000000011 0000001100000100 0000000000000101 0000000100000110 0000001000000111 0000001100001000 0000000000001001 00000001etc.
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.
What he means is that :
x modulo y = (x & (y − 1))
When y is a power of 2.
Example:
0110010110 (406) modulo0001000000 (64) =0000010110 (22)^^^^<- ignore these bits
Using your example now :
1011000111011010 (45530) modulo0000000000000001 (2 power 0) =0000000000000000 (0)^^^^^^^^^^^^^^^^<- ignore these bits1011000111011010 (45530) modulo0000000000010000 (2 power 4) =0000000000001010 (10)^^^^^^^^^^^^<- ignore these bits
Consider when you take a number modulo 10. If you do that, you just get the last digit of the number.
334 % 10 = 4 12345 % 10 = 5
Likewise if you take a number modulo 100, you just get the last two digits.
334 % 100 = 34 12345 % 100 = 45
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.