Simvik

Write a bit

Force one bit to a given state. An easy embedded C problem (Bit manipulation), run and graded in the browser.

easy · Bit manipulation · masks

Return reg with bit pos set to 1 when on is true and cleared to 0 when it is false. pos is between 0 and 31.

Starter code

uint32_t write_bit(uint32_t reg, uint8_t pos, bool on) {
  // Make bit `pos` equal to `on`, leaving every other bit unchanged.
  return reg;
}

Example tests

Turn a bit on

printf("0x%08X\n", write_bit(0x00000000, 2, true));

Expected output:

0x00000004

Turn a bit off

printf("0x%08X\n", write_bit(0x000000FF, 2, false));

Expected output:

0x000000FB

Learn it first

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

More Bit manipulation problems