Simvik

Power of two

Decide whether a value is a power of two without a loop. An easy embedded C problem (Bit manipulation), run and graded in the browser.

easy · Bit manipulation · bit-tricks

Return true if x is a power of two (1, 2, 4, 8, ...). Zero is not a power of two.

Solve it without a loop.

Starter code

bool is_pow2(uint32_t x) {
  // A power of two has exactly one bit set.
  return false;
}

Example tests

A power of two

printf("%d\n", is_pow2(8));

Expected output:

1

Not a power of two

printf("%d\n", is_pow2(12));

Expected output:

0

Learn it first

  • Bit manipulation · Masks, shifts, fields and the idioms every register access is built from.

More Bit manipulation problems