Check if a number is a power of two with x && !(x & (x - 1))
Test for a power of two with one subtraction and one AND on an unsigned value, and keep the leading x check so that zero is not reported as one.
Subtracting one from a power of two turns its single set bit into zero and every bit below it into one, so x & (x - 1) clears the lowest set bit. The result is zero only when at most one bit was set. That is the whole test, with one catch: zero also gives zero, which is why the x && in front is not decoration.
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
static bool is_pow2(uint32_t x) {
return x && !(x & (x - 1));
}
int main(void) {
uint32_t tests[] = {0, 1, 6, 64, 96, 0x80000000u};
for (int i = 0; i < 6; i++)
printf("%u -> %d\n", tests[i], is_pow2(tests[i]));
return 0;
}0 -> 0
1 -> 1
6 -> 0
64 -> 1
96 -> 0
2147483648 -> 1Keep the argument unsigned. With a signed int, x - 1 overflows when x is INT_MIN, which is undefined behaviour, while uint32_t arithmetic wraps by definition. In C++20 you do not need the trick at all: std::has_single_bit in <bit> does the same thing and says so in its name.