Simvik

Write a bit field

Replace a multi-bit field inside a register value. A medium embedded C problem (Bit manipulation), run and graded in the browser.

medium · Bit manipulation · fields · masks

Return reg with the width-bit field at position pos replaced by value. Bits outside the field must not change.

If value has bits above width, ignore them: they must not leak into neighbouring fields. width is between 1 and 32 and pos + width never exceeds 32.

Starter code

uint32_t set_field(uint32_t reg, uint8_t pos, uint8_t width, uint32_t value) {
  // Replace bits [pos + width - 1 : pos] of reg with the low `width` bits of value.
  return reg;
}

Example tests

Clear a nibble

printf("0x%08X\n", set_field(0xFFFFFFFF, 8, 4, 0x0));

Expected output:

0xFFFFF0FF

Write a 3-bit mode

printf("0x%08X\n", set_field(0x00000000, 4, 3, 0x5));

Expected output:

0x00000050

Learn it first

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

More Bit manipulation problems