Bits And The Power of Two

January 27th, 2007 by Lorenzo

Sometimes it is useful to find out if a particular integer represents a power of two. You can find that out with a simple trick.

A power of two in binary is represented by a all zeros, except for a single one. For example 00010000 is a power of two (2^4).
In fact you can calculate the n-th power of 2 with:

int power2(int n)
{
     return (1<

If you subtract one from a power of two, you obtain a number which binary representation is a sequence of ones. Example in binary:

00010000 - 1 = 00001111

If you take this number and perform a logical AND with the original power of two you obtain a flat zero!
Example:

00010000 &
00001111
———
00000000

If you have any other number that is not a power of two, this doesn’t work anymore and you’d never obtain a zero.
For example let’s take 18, which is not a power of two.

18 in binary is 00010010
00010010 - 1 = 00010001

00010010 &
00010001 =
———
00010000

Another example. Let’s take 14 which is another number that is not a power of two:

14 in binary is 00001110
00001110 - 1 = 00001101

00001101 &
00001110 =
———
00001100

In general you’ll find that the result of (X-1)&X always contains at least a one… unless X is a power of two! Cool!

For this simple reason you can find out if an integer is a power of two with something like:

boolean isPowerOf2(int x)
{
    return ((x-1) & x)==0;
}

Enjoy! :)

5 Responses to “Bits And The Power of Two”

  1. bloid Says:

    What about:

    return ( x & 1 ) == 0 ;

    ?

  2. Lorenzo Says:

    No. That would only tell you if a number x is divisible by 2. It would not tell you if x it is a power of 2.
    While all powers of 2 are even, it is not true that all even numbers are also powers of 2.
    For example 6 is divisible by 2, but it is not a power of 2.

  3. drostowsky Says:

    This is a famous MSFT interview question too. :) “Write me a function that tests if a number is a power of 2…” This is good info to remember!

    Keep on coding!
    Dave

  4. Nathan Says:

    I think there are two special cases that will cause isPowerOf2 to give a false positive: 0 and -MAXINT-1.

  5. Aaron Says:

    Has someone been interviewing with google?

Leave a Reply

You must be logged in to post a comment.