Ten Ways to Check if an Integer Is a Power Of Two in C

http://www.exploringbinary.com/ten-ways-to-check-if-an-integer-is-a-power-of-two-in-c/


To write a program to check if an integer is a power of two, you could follow two basic strategies: check the number based on its decimal value, or check it based on its binary representation. The former approach is more human-friendly but generally less efficient; the latter approach is more machine-friendly but generally more efficient. We will explore both approaches, comparing ten different but equivalent C functions.

Decimal-Based Approaches to Checking for Powers of Two

Decimal integers in C source code are converted to binary form, but technically you don’t need to know that; you can still treat them as decimal in the algorithms you write. The first six functions presented are based on that view.

1. Divide by Two

This function implements the “pencil and paper” method of checking whether an integer is a power of two. It repeatedly divides x, the 32-bit unsigned integer being tested, by 2. It divides until either the quotient becomes 1, in which case x is a power of two, or the quotient becomes odd before reaching 1, in which case x is not a power of two.

int isPowerOfTwo (unsigned int x)
{
 while (((x % 2) == 0) && x > 1) /* While x is even and > 1 */
   x /= 2;
 return (x == 1);
}

2. Check All

This function hard codes the first 32 nonnegative powers of two into one `OR’ expression. If x is a power of two less than 2,147,483,648, or 231, the expression will short-circuit according to C-semantics. If x is not a power of two or is 231 , all 32 values will be inspected.

int isPowerOfTwo (unsigned int x)
{
 return (
   x == 1 || x == 2 || x == 4 || x == 8 || x == 16 || x == 32 ||
   x == 64 || x == 128 || x == 256 || x == 512 || x == 1024 ||
   x == 2048 || x == 4096 || x == 8192 || x == 16384 ||
   x == 32768 || x == 65536 || x == 131072 || x == 262144 ||
   x == 524288 || x == 1048576 || x == 2097152 ||
   x == 4194304 || x == 8388608 || x == 16777216 ||
   x == 33554432 || x == 67108864 || x == 134217728 ||
   x == 268435456 || x == 536870912 || x == 1073741824 ||
   x == 2147483648);
}

3. Check Next Power

This function computes each power of two incrementally, quitting when x is less than or equal to the current power of two.

int isPowerOfTwo (unsigned int x)
{
 unsigned int powerOfTwo = 1;

 while (powerOfTwo < x && powerOfTwo < 2147483648)
   powerOfTwo *= 2;
 return (x == powerOfTwo);
}

The hard coded constant for 231 prevents overflowing the 32-bit unsigned integer.

4. Linear Search

This function is the same as the Check Next Power algorithm except that the powers of two are precomputed and stored in a table.

int isPowerOfTwo (unsigned int x)
{
 unsigned int powersOfTwo[32] =
   {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,
    65536,131072,262144,524288,1048576,2097152,4194304,8388608,
    16777216,33554432,67108864,134217728,268435456,536870912,
    1073741824,2147483648};

 int exponent = 0;

 while (powersOfTwo[exponent] < x && exponent < 31)
   exponent++;
 return (x == powersOfTwo[exponent]);
}

5. Binary Search

This function does a binary search of powers of two stored in a table.

int isPowerOfTwo (unsigned int x)
{
 unsigned int powersOfTwo[32] =
   {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,
    65536,131072,262144,524288,1048576,2097152,4194304,8388608,
    16777216,33554432,67108864,134217728,268435456,536870912,
    1073741824,2147483648};

 unsigned char isAPowerOfTwo;

 int interval = 16;
 int exponent = interval; /* Start out at midpoint */ 

 switch (x) {
   case 0:
	isAPowerOfTwo = 0;
        break;
   case 1: /* Special case makes binary search easier */
	isAPowerOfTwo = 1;
	break;
   default:
     while (x != powersOfTwo[exponent] && interval > 1) {
       if (x < powersOfTwo[exponent])
        exponent -= interval/2;
       else
        exponent += interval/2;
       interval /= 2;
     }
     isAPowerOfTwo = x == powersOfTwo[exponent];
 }

 return (isAPowerOfTwo);
}

6. Log Search

This function uses logarithms to determine if x is a power of two, put perhaps not in the way you’d expect. The log in base 2 of x, or log2(x), is the exponent n to which 2 is raised to get x. Mathematically, if n is an integer, then x is a power of two; if n is not an integer, then x is not. But in a computer, when floating-point calculations are used, things don’t always work out this neatly (see section “Beware of Logarithms” for more about this.)

In this case, the solution is to choose the two integral exponents that bound the logarithm and compare x to their corresponding powers of two; x can only be a power of two if it matches one of the two.

Since C does not have a built-in function for log2(x), a change of base is used to compute it.


int isPowerOfTwo (unsigned int x)
{
 int exponent = 0;
 unsigned char isAPowerOfTwo;

 unsigned int powersOfTwo[32] =
   {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,
    65536,131072,262144,524288,1048576,2097152,4194304,8388608,
    16777216,33554432,67108864,134217728,268435456,536870912,
    1073741824,2147483648};

 if (x == 0 || x > 2147483648)
   isAPowerOfTwo = 0;
 else
   {
    exponent = (int)(log((double)x)/log(2.0)); /* Log base 2 */
    isAPowerOfTwo = (x == powersOfTwo[exponent] ||
                             x == powersOfTwo[exponent+1]);
   }
 return (isAPowerOfTwo);
}

When the exponent is 31, the OR expression will short-circuit before trying to access the table out-of-bounds.

Binary-Based Approaches to Checking for Powers of Two

An arguably more direct way to check if an integer is a power of two is to access its binary representation. An unsigned integer is a power of two if and only if it has exactly one 1 bit. The four functions below are based on that observation.

7. Count Ones

This function is probably the first that comes to mind — counting 1 bits. Of course you don’t need to count all 1 bits; you can stop counting if more than one 1 bit is found.

int isPowerOfTwo (unsigned int x)
{
 unsigned int numberOfOneBits = 0;

 while(x && numberOfOneBits <=1)
   {
    if ((x & 1) == 1) /* Is the least significant bit a 1? */
      numberOfOneBits++;
    x >>= 1;          /* Shift number one bit to the right */
   }

 return (numberOfOneBits == 1); /* 'True' if only one 1 bit */
}

8. Shift Right

This function is the equivalent of the Divide by Two algorithm. Dividing a binary integer by 2 is the same as shifting it right one bit, and checking whether a binary integer is odd is the same as checking if its least significant bit is 1.

int isPowerOfTwo (unsigned int x)
{
 while (((x & 1) == 0) && x > 1) /* While x is even and > 1 */
   x >>= 1;
 return (x == 1);
}

The only way the statement “x == 1” becomes true is when there is only one 1 bit in x to start with.

9. Decrement and Compare

This function is a common one-liner you’ll find on the Web, and is how the check is implemented in malloc.c in the GNU C Library (glibc).

int isPowerOfTwo (unsigned int x)
{
  return ((x != 0) && !(x & (x - 1)));
}

There are two halves to the expression: x != 0 and !(x & (x – 1)). The first half makes 0 a special case, since the second half only works correctly for positive numbers. The second half — the interesting part of the expression — is true when x is a power of two and false when x is not. Let’s see why.

Let n be the position of the leftmost 1 bit if x. If x is a power of two, its lone 1 bit is in position n. This means x – 1 has a 0 in position n. To see why, recall how binary subtraction works. When subtracting 1 from x, the borrow propagates all the way to position n; bit n becomes 0 and all lower bits become 1. Now, since x has no 1 bits in common with x – 1, x & (x – 1) is 0, and !(x & (x – 1)) is true.

Here are some examples (I’ll use 8-bit unsigned integers to keep things manageable):

Decrement and Compare, when x is a power of two
x x – 1 x & (x – 1)
00000001 00000000 00000000
00000100 00000011 00000000
00010000 00001111 00000000

If x is not a power of two, x – 1 has a 1 in position n. This is because the borrow will not propagate to position n. Subtraction borrows from the lowest 1 bit, which by virtue of x not being a power of two, is before position n. The lowest 1 bit is like a firewall that prevents the borrow from reaching position n. Since x and x – 1 have at least one 1 bit in common — at position n — x & (x – 1) is non-zero, and !(x & (x – 1)) is false.

Here are some examples:

Decrement and Compare, when x is a NOT power of two
x x – 1 x & (x – 1)
00000011 00000010 00000010
00000110 00000101 00000100
00001011 00001010 00001010
00011100 00011011 00011000

10. Complement and Compare

This function is another one-liner that can be found on the Web. At it’s core, it is similar to the Decrement and Compare method.

int isPowerOfTwo (unsigned int x)
{
  return ((x != 0) && ((x & (~x + 1)) == x));
}

The first half of the expression ensures that x is a positive integer. The second half of the expression, (x & (~x + 1)) == x, is true only when x is a power of two. It compares x with its two’s complement. The two’s complement of x is computed with ~x + 1, which inverts the bits of x and adds 1 (~x + 1 is equivalent to -x, but negation is technically illegal for an unsigned integer).

Let n be the position of the leftmost 1 bit if x. If x is a power of two, its lone 1 bit is in position n. This means ~x has a 0 in position n and 1s everywhere else. When 1 is added to ~x, all positions below n become 0 and the 0 at position n becomes 1. In other words, the carry propagates all the way to position n. So what happens is this: negating x inverts all its bits, but adding 1 inverts them back, from position n on down. So, (x & (~x + 1)) == x is true.

Here are some examples:

Complement and Compare, when x is a power of two
x ~x ~x + 1 x & (~x + 1)
00000001 11111110 11111111 00000001
00000100 11111011 11111100 00000100
00010000 11101111 11110000 00010000

If x is not a power of two, ~x has at least one 0 below position n. When 1 is added, the carry will not propagate to position n. In other words, not all bits from position n and below will be inverted back. This means (x & (~x + 1)) == x is false.

Here are some examples:

Complement and Compare, when x is a NOT power of two
x ~x ~x + 1 x & (~x + 1)
00000011 11111100 11111101 00000001
00000110 11111001 11111010 00000010
00001011 11110100 11110101 00000001
00011100 11100011 11100100 00000100

Endianness

In case you were wondering, these algorithms are endian-independent. Integers are accessed numerically and logically with arithmetic, bitwise, and logical operators, not as byte strings. (If we were to check the binary representation of floating-point numbers, we would have to take endianness into account to access the fields).

Comparing the Algorithms

As for readability, the decimal-based algorithms are more human-friendly. Divide by Two and Check Next Power are methods you might use if you had to check by hand; Check All, Linear Search, Binary Search, and Log Search are methods you might use if you had a table of powers of two to consult. The binary-based algorithms are designed for machines, but if you understand how they work, you’ll appreciate their elegance.

As for performance, the table below shows how the algorithms stack up. I wrote a test case to call each function with all 232 unsigned integer values. I used the Microsoft Visual C++ 2008 Express Edition compiler and ran the program on an Intel Core Duo machine. I repeated the test case three times and computed the average running time for each function.

The algorithms are listed from fastest to slowest. As you might expect, the binary-based functions are generally the fastest.

Running Time to Check All 232 Integers
Algorithm Elapsed Time
No. Name
10 Complement and Compare 6 minutes, 43 seconds
9 Decrement and Compare 6 minutes, 51 seconds
8 Shift Right 7 minutes, 2 seconds
2 Check All 8 minutes, 42 seconds
7 Count Ones 10 minutes, 14 seconds
1 Divide by Two 10 minutes, 44 seconds
3 Check Next Power 14 minutes, 8 seconds
5 Binary Search 18 minutes, 17 seconds
6 Log Search 21 minutes, 58 seconds
4 Linear Search 26 minutes, 20 seconds

How NOT to Check

Beware of Signed Integers

If you want to check signed integers, you either have to modify the routines above or filter out negative numbers before calling them. As an example, consider Decrement and Compare. If you switched its parameter from unsigned integer to signed integer, it would handle all negative numbers correctly except one: -2,147,483,648. The problem is that in two’s complement, the largest negative integer of any given word size looks like a power of two. In this case, that’s -231, or -2,147,483,648, and it looks like this: 10000000000000000000000000000000. The fix is to change the check “x != 0” to “x > 0”.

Beware of Logarithms

The following code is wrong:

int isPowerOfTwo(unsigned int x)
{
  /* Incorrect way to check */
 double exponent;
 unsigned char isAPowerOfTwo;

 if (x == 0)
   isAPowerOfTwo = 0;
 else
   {
    exponent = log((double)x)/log(2.0); /* Log base 2 */
    isAPowerOfTwo = int(exponent) == exponent;
   }
 return (isAPowerOfTwo);
}

As I hinted in the Log Search algorithm section, the logarithm calculation can return nonintegers when an integer is expected. This is true of the above function, and specifically, for two powers of two: 536,870,912 (2^29) and 2,147,483,648 (2^31). It computes log2(229) as 29.000000000000004, and log2(231) as 31.000000000000004. These are extremely close to, but are not, integers.

You might think you could build in a tolerance so that “close” values are treated as integers. But where do you draw the line? log2(229 + 1) = 29.000000003, and log2(231 + 1) = 31.0000000007. Should those be treated as integers? No!

The solution is to choose the two integral exponents that bound the logarithm and compare x to their corresponding powers of two. That is what we did in section “Log Search”.

Determining Which Power of Two an Integer Is

If you also want to know which power of two an integer is, that is, what its exponent is, the functions above must be modified. The Linear Search and Log Search functions require the least change; they just have to return the computed exponent. The other functions would need to be changed to varying degrees, some to the point where the code would change dramatically.

Summary

I presented ten C functions that showed different ways of checking whether an integer is a power of two. No doubt you could implement them differently, like using macros instead of functions. Beyond that, you could modify them to work for different word sizes. You could also translate them easily to other languages, like PHP, Java, and of course, C++.

The two approaches I discussed should give you more insight into the nature of the powers of two, both as decimal and binary numbers.

Dingbat

5 Responses to “Ten Ways to Check if an Integer Is a Power Of Two in C”

  1. Jeff Says:

    A variation on counting the ones (#7), though I don’t know how fast it might be, uses a lookup table. For example, take 4-bits at a time (shifting and masking as necessary) and use the value to index into an array like:

    int bitpop[16] = { 0, 1, 1, 2 … 2, 3, 3, 4 };

    Shift and mask by 8 and index into a 256-element array fir more speed (and memory).

    Offsetting the slowness of counting ones is you get back more information than just whether or not a value is a power of two.

  2. Rick Regan Says:

    Jeff,

    I coded your idea, but in the spirit of how I coded #7 (quitting once the bit count exceeds 1):

    int isPowerOfTwo (unsigned int x)
    {
     unsigned int numberOfOneBits = 0;
     unsigned int oneBits[16] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
    
     while(x && numberOfOneBits < =1)
       {
        numberOfOneBits += oneBits[x & 0xF];
        x >>= 4; /* Examine next 4 bits */
       }
    
     return (numberOfOneBits == 1); /* 'True' if only one 1 bit */
    }
    

    This ran in 16 minutes, 38 seconds 13 minutes, 1 second, making it slower than #7.

    The algorithms with the table lookups seem good in principle, but are among the slowest. Maybe they’d compare better for 64-bit integers? (Of course humans may no longer inhabit the planet when those runs finish ;) )

  3. Jeff Says:

    Ii confess my surprise at the lookup table’s poor performance.

    So I tried it on my machine (Mac w/ 2.16 GHz Intel Cor 2 Duo, and gcc 4.0.1 (Apple Inc. build 5465, using only default options).

    I also added a modified lookup function where the lookup array was a global. I repeated the three cases (the first two literally cut-and-pasted from above) 10 times each, and got…

    #7: 152 seconds
    lookup table w/ local array: 105 s
    lookup table w/ global array: 80 s

    So, one could conclude that
    a) chip and compiler can make a BIG difference
    b) you need a faster machine! :) :)

  4. Rick Regan Says:

    Jeff,

    I ran them on an Intel Core Duo processor T2050, 1.60 GHz. But that’s only part of the difference. I didn’t mention that my loop that called each function 2^32 times also included a verification that the result was correct (seems kind of recursive, doesn’t it?). I really shouldn’t have left the checks in after I verified the algorithms, so I repeated the runs without them and updated the tables above. The algorithms still perform in the same relative order.

    As an aside, I also re-ran your “table method” algorithm against #7 without short-circuiting the while loops (so counted all 1 bits). Your table algorithm did indeed perform better in that case.

  5. Find if a number is a power of two, v2 « Kami Kode Says:

    [...] to how to find using only bitwise operators, if a number is a power of two. This site led me to another site with 10 different ways to check if an integer is a power of two; the one I need is a slight [...]

Leave a Comment