Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise and in place of modulus operator

Tags:

algorithm

We know that for example modulo of power of two can be expressed like this:

x % 2 inpower n == x & (2 inpower n - 1). 

Examples:

x % 2 == x & 1 x % 4 == x & 3 x % 8 == x & 7  

What about general nonpower of two numbers?

Let's say:

x % 7==?

like image 830
dato datuashvili Avatar asked Jun 18 '10 19:06

dato datuashvili


People also ask

Is modulus a bitwise operator?

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

What is & In bitwise operator?

The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise AND operator must have integral types.

Are bitwise and and/or associative?

Because the bitwise AND operator has both associative and commutative properties, the compiler can rearrange the operands in an expression that contains more than one bitwise AND operator.


1 Answers

First of all, it's actually not accurate to say that

x % 2 == x & 1 

Simple counterexample: x = -1. In many languages, including Java, -1 % 2 == -1. That is, % is not necessarily the traditional mathematical definition of modulo. Java calls it the "remainder operator", for example.

With regards to bitwise optimization, only modulo powers of two can "easily" be done in bitwise arithmetics. Generally speaking, only modulo powers of base b can "easily" be done with base b representation of numbers.

In base 10, for example, for non-negative N, N mod 10^k is just taking the least significant k digits.

References

  • JLS 15.17.3 Remainder Operator %
  • Wikipedia/Modulo Operation
like image 144
polygenelubricants Avatar answered Sep 23 '22 02:09

polygenelubricants