Wednesday, September 12, 2012

How do you find whether a number is power of 2.

An interesting question is how do find whether a number is a power of 2?

Well it is simple actually. Lets take for example the number 256, which is 2 to the power 8. Lets write the binary representation of 256

2^8 = 256 = 1 0000 0000
2^7 = 128 = 0 1000 0000
2^6 = 64   = 0 0100 0000
2^5 = 32   = 0 0010 0000
2^4 = 16   = 0 0001 0000
2^3 = 8     = 0 0000 1000
2^2 = 4     = 0 0000 0100
2^1 = 2     = 0 0000 0010
2^0 = 1     = 0 0000 0001


The commonality is that all these numbers have only a single bit set. So our requirement for a number to be power of 2 is It should have only 1 bit set (to 1).

Now the next challenge is how to convert this into a C code. Well you could write some algorithm to
iterate over the bits and make sure there is only a single bit set. It would work but it requires writing a loop and doing some bit manipulations to iterate over the binary number.

What about the following approach:
We basically need to ensure that only a single bit is set. Lets take 128
128 = 0 1000 0000
127 = 0 0111 1111
if we AND these two numbers we will get 0 0000 0000, similarly
256 = 1 0000 0000
255 = 0 1111 1111
if we AND these two numbers we will get 0 0000 0000.
You can try this for other power of 2 numbers. So now we are seeing an approach which is
for a number to be power of 2 if we AND the number and number - 1 its result should be 0
bool bIsPowerOfTwo = number & (number - 1 ) == 0 ? true : false;

This will work, however a better code is:
bool bIsPowerOfTwo = number && ( number & (number - 1) == 0 );




No comments: