Simvik

Round up to a power of two

Find the smallest power of two that is not less than a value. A medium embedded C problem (Bit manipulation), run and graded in the browser.

medium · Bit manipulation · bit-tricks · buffers

Return the smallest power of two that is greater than or equal to x. x is between 1 and 0x80000000.

A buffer allocator uses this to round a requested size up to a size it can index with a mask.

Starter code

uint32_t next_pow2(uint32_t x) {
  // 5 -> 8, 16 -> 16, 17 -> 32
  return x;
}

Example tests

Between two powers

printf("%u\n", next_pow2(5));

Expected output:

8

Already a power of two

printf("%u\n", next_pow2(16));

Expected output:

16

Learn it first

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

More Bit manipulation problems