Simvik

Extract a bit field

Read a field of a given width and position out of a register value. An easy embedded C problem (Bit manipulation), run and graded in the browser.

easy · Bit manipulation · fields · masks

Registers pack several settings into one word. Return the field of width bits whose least significant bit is at position pos, shifted down so it starts at bit 0.

width is between 1 and 32 and pos + width never exceeds 32. For example, with reg = 0xABCD1234, the 8-bit field at position 8 is 0x12.

Starter code

uint32_t get_field(uint32_t reg, uint8_t pos, uint8_t width) {
  // Return bits [pos + width - 1 : pos] of reg, right-aligned.
  return 0;
}

Example tests

A byte in the middle

printf("0x%X\n", get_field(0xABCD1234, 8, 8));

Expected output:

0x12

The top nibble

printf("0x%X\n", get_field(0xABCD1234, 28, 4));

Expected output:

0xA

Learn it first

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

More Bit manipulation problems