Search code examples
operatorsbit-manipulationmodulusand-operator

Is Modulus more efficient than And operator for finding halfs


I started playing with bitwise operators today I noticed that the & operator could be used to find if something is even or not.

100 & 1;//Gives 0
101 & 1;//Gives 1

Zeros for even and ones for odds.

So, I am currently wondering which is a more efficient method of finding if something is even:

A)if (n & 1 == 0) isEven = true;

or

B)if(n % 2 == 0) isEven = true;

Also, is there a more efficient way to find if something is even?

P.S. There is no reason that I need for an efficient way of finding if something is an even number, I am just genuinely curious.


Solution

  • Compilers are pretty smart; if either is actually faster in practice, both &1 and %2 will quite possibly compile to the same - faster - code.

    With a stupid compiler, I'd place a bet on &1 being at least as fast as the alternative since it maps to bit operations which is a very basic operation for pretty much any CPU.

    Modulo may be as fast on some CPUs, but definitely not so on low cost embedded CPUs.