Simvik

Hygienic register macros

Fix four bit-manipulation macros that break on compound arguments. A medium embedded C problem (Registers and memory-mapped I/O), run and graded in the browser.

medium · Registers and memory-mapped I/O · macros · preprocessor

The starter macros work for simple arguments and fail for expressions, because macro expansion is textual and operator precedence regroups the pieces.

Fix all four so they behave correctly for any argument expression:

  • BIT(n): a mask with bit n set
  • SET_BITS(reg, mask): set the masked bits of reg
  • CLEAR_BITS(reg, mask): clear the masked bits of reg
  • READ_FIELD(reg, mask, pos): reg masked with mask, then shifted right by pos

Starter code

#define BIT(n) 1u << n
#define SET_BITS(reg, mask) reg |= mask
#define CLEAR_BITS(reg, mask) reg &= ~mask
#define READ_FIELD(reg, mask, pos) reg & mask >> pos

Example tests

Set two bits

uint32_t r = 0;
SET_BITS(r, BIT(0) | BIT(4));
printf("0x%02X\n", r);

Expected output:

0x11

Clear two bits

uint32_t r = 0xFF;
CLEAR_BITS(r, BIT(0) | BIT(1));
printf("0x%02X\n", r);

Expected output:

0xFC

Learn it first

  • Registers, volatile and const · How C talks to hardware: memory-mapped registers, what volatile and const promise, register structs and read-modify-write.

More Registers and memory-mapped I/O problems