Reputation: 1167
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.
Upvotes: 0
Views: 41
Reputation: 3891
More efficient way:
isEven = !(n & 1);
Regarding using modulto operation %2 or so on:
On some compilers, it can generate longest/slowest code for signed integers, because of, for example:
-5 % 2 == -1
For unsigned "n", usually compiler generate same code for both operations:
n % 2
n & 1
Upvotes: 1
Reputation: 180917
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.
Upvotes: 2