The power of bitwise operators are immense. Sometimes thinking in terms of arithmetical operators cost you lots of CPU time when compared to bitwise operators. So given a problem its obvious for us to think in terms of arithmetical solutions, but try to search for a bitwise solution and compare it with previous one. You can end up in a very powerful algorithm too. Now I wish to share one such case where the use of bitwise operator avoids the use of a loop too.
Problem Statement: Given a number, check whether its a positive power of two or not.
First I would like to give a simple arithmetical solution. Here I have given the solution in the syntax of C as the problem we are talking is algorithmic and not language oriented. Moreover, everyone would be able to understand the program flow in C easily.
This is quite a good algorithm of order O(log2n), that is, given a number n, it will take log2n operations to find the result. So, if n is 256, then 8 operations are required to produce the result. The algorithm that we have come up with works at an amazing rate. O(log2n) is a very good algorithm. Still, if it can be reduced further to O(1) it will be great isn't it. Bitwise operators come to the rescue.
Now see the program below which is the bitwise algorithm for solving the same problem.
This bitwise algorithm has only one operation which checks a&(a-1) is 0 or not. If its 0, then its a power of 2 otherwise its not. How? It seems amazing isn't it? Let's see.
First note the binary representations of the powers of 2.
Now check out the other part, binary representations of (2^n)-1.
A sample and operation of a power of 2 and its previous number.
8&7 => 00001000 & 00000111 => 00000000
And when its not a power of 2
6&5 => 00000110 & 00000101 => 00000100
Bitwise representation of a number which is power of 2 varies at every bit from the previous numbers bitwise representation.
But when its not a power of two, they have at least one '1' in common position. Now its clear that whenever you make an AND operation on the numbers which is power of 2 and one less than that, ultimately you end up at zero. Similarly, if the number is not a power of 2, you will end up in a non zero number.
This is an example to show the power of bitwise operators. Hope you enjoyed.
- Fareez Ahamed K.N.