1011000111011010
)?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 =)
It determines whether integer is power of 2 or not. If (x & (x-1)) is zero then the number is power of 2. For example, let x be 8 ( 1000 in binary); then x-1 = 7 ( 0111 ). This outputs the bit is power of 2 .
Modulo can be easily translated into a bitwise AND if the divisor is a power of two.
The modulo operator, denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division. produces the remainder when x is divided by y.
Multiply any Number with using Bitwise Operator in C++ The left shift (<<) operator is used for the multiplication whereas the right shift (>>) is used for the division. The multiplication of two numbers x, y can be written as x * y = (x * 2) * (y / 2) if y is even else it's equal to x * y = (x * y) * (y / 2) + x.
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.
What he means is that :
x modulo y = (x & (y − 1))
When y is a power of 2.
Example:
0110010110 (406) modulo 0001000000 (64) = 0000010110 (22) ^^^^<- ignore these bits
Using your example now :
1011000111011010 (45530) modulo 0000000000000001 (2 power 0) = 0000000000000000 (0) ^^^^^^^^^^^^^^^^<- ignore these bits 1011000111011010 (45530) modulo 0000000000010000 (2 power 4) = 0000000000001010 (10) ^^^^^^^^^^^^<- ignore these bits
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With