I need a function like this:
// return true if 'n' is a power of 2, e.g.
// is_power_of_2(16) => true
// is_power_of_2(3) => false
bool is_power_of_2(int n);
Can anyone suggest how I could write this?
I need a function like this:
// return true if 'n' is a power of 2, e.g.
// is_power_of_2(16) => true
// is_power_of_2(3) => false
bool is_power_of_2(int n);
Can anyone suggest how I could write this?
(n & (n - 1)) == 0 is best. However, note that it will incorrectly return true for n=0, so if that is possible, you will want to check for it explicitly.
http://www.graphics.stanford.edu/~seander/bithacks.html has a large collection of clever bit-twiddling algorithms, including this one.
A power of two will have just one bit set (for unsigned numbers). Something like
bool powerOfTwo = !(x == 0) && !(x & (x - 1));
Will work fine; one less than a power of two is all 1s in the less significant bits, so must AND to 0 bitwise.
As I was assuming unsigned numbers, the == 0 test (that I originally forgot, sorry) is adequate. You may want a > 0 test if you're using signed integers.
Powers of two in binary look like this:
1: 0001
2: 0010
4: 0100
8: 1000
Note that there is always exactly 1 bit set. The only exception is with a signed integer. e.g. An 8-bit signed integer with a value of -128 looks like:
10000000
So after checking that the number is greater than zero, we can use a clever little bit hack to test that one and only one bit is set.
bool is_power_of_2(int x) {
return x > 0 && !(x & (x−1));
}
For more bit twiddling see here.
In C++20 there is std::has_single_bit which you can use for exactly this purpose if you don't need to implement it yourself:
#include <bit>
static_assert(std::has_single_bit(16));
static_assert(!std::has_single_bit(15));
Note that this requires the argument to be an unsigned integer type.
This is probably the fastest, if using GCC. It only uses a POPCNT cpu instruction and one comparison. Binary representation of any power of 2 number, has always only one bit set, other bits are always zero. So we count the number of set bits with POPCNT, and if it's equal to 1, the number is power of 2. I don't think there is any possible faster methods. And it's very simple, if you understood it once:
if(1==__builtin_popcount(n))
This isn't the fastest or shortest way, but I think it is very readable. So I would do something like this:
bool is_power_of_2(int n)
int bitCounter=0;
while(n) {
if ((n & 1) == 1) {
++bitCounter;
}
n >>= 1;
}
return (bitCounter == 1);
}
This works since binary is based on powers of two. Any number with only one bit set must be a power of two.
Another way to go (maybe not fastest) is to determine if ln(x) / ln(2) is a whole number.