Simvik

Lowest set bit

Find the index of the least significant set bit. An easy embedded C problem (Bit manipulation), run and graded in the browser.

easy · Bit manipulation · scanning

Return the position of the lowest set bit of x, where bit 0 is the least significant. Return -1 if x is 0.

Interrupt dispatchers use this to find which pending flag to service first.

Starter code

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

Example tests

Single bit

printf("%d\n", find_first_set(0x08));

Expected output:

3

Several bits

printf("%d\n", find_first_set(0x14));

Expected output:

2

Learn it first

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

More Bit manipulation problems