Simvik

Highest set bit

Find the index of the most significant set bit. A medium embedded C problem (Bit manipulation), run and graded in the browser.

medium · Bit manipulation · scanning · log2

Return the position of the highest set bit of x, or -1 if x is 0. For a non-zero value this is the integer part of its base-2 logarithm.

Starter code

int highest_bit(uint32_t x) {
  // Return the index of the highest 1 bit, or -1 when x is 0.
  return -1;
}

Example tests

Bit 0

printf("%d\n", highest_bit(1));

Expected output:

0

Several bits

printf("%d\n", highest_bit(0x50));

Expected output:

6

Learn it first

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

More Bit manipulation problems