INTERMEDIATE
Check Power of Two
Determine if a given number is a power of 2 using only bitwise operations.
Silicon Logic
A power of 2 has exactly one set bit in its binary representation. Subtracting 1 from such a
number
clears that set bit and sets all lower bits to 1. Therefore, performing a bitwise AND between
n and n-1 results in 0.
If (n & (n - 1)) == 0 and
n > 0, then n is a power of 2.
Example (n = 16):
n : 00010000 (16)
n - 1 : 00001111 (15)
-------------------
& : 00000000 (0) → IS POWER OF 2
n : 00010000 (16)
n - 1 : 00001111 (15)
-------------------
& : 00000000 (0) → IS POWER OF 2
Example (n = 12):
n : 00001100 (12)
n - 1 : 00001011 (11)
-------------------
& : 00001000 (8) → NOT POWER OF 2
n : 00001100 (12)
n - 1 : 00001011 (11)
-------------------
& : 00001000 (8) → NOT POWER OF 2
#include <stdint.h>
#include <stdbool.h>
// Returns true if n is a power of 2
bool isPowerOfTwo(uint32_t n) {
if (n == 0) return false;
return (n & (n - 1)) == 0;
}
int main() {
uint32_t val = 16;
bool result = isPowerOfTwo(val);
return 0;
}