Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 =)

like image 995
Zo Has Avatar asked Jul 12 '11 20:07

Zo Has


People also ask

How do you find 2 power n using Bitwise Operators?

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 .

Is modulus a Bitwise operator?

Modulo can be easily translated into a bitwise AND if the divisor is a power of two.

What is the mod (%) operator?

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.

How do Bitwise Operators multiply by 2?

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.


2 Answers

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.

like image 146
BlueRaja - Danny Pflughoeft Avatar answered Oct 08 '22 00:10

BlueRaja - Danny Pflughoeft


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 
like image 23
user703016 Avatar answered Oct 08 '22 01:10

user703016