</>EmbeddedInterview

How do you extract or insert a bit field?

EasyBit Manipulation

Short answer: To read a field, shift it down and mask: (reg >> shift) & ((1u << width) - 1). To write it, clear the field with the inverted mask and OR in the new value shifted into place.

#define FIELD_GET(reg, shift, width)  (((reg) >> (shift)) & ((1u << (width)) - 1u))

static inline uint32_t field_set(uint32_t reg, unsigned shift, unsigned width, uint32_t val)
{
    uint32_t mask = ((1u << width) - 1u) << shift;   /* width < 32 */
    return (reg & ~mask) | ((val << shift) & mask);
}

Example: a clock prescaler in bits 6..4 of a register.

uint32_t cfg = 0x1234;
unsigned psc = FIELD_GET(cfg, 4, 3);     /* (0x1234 >> 4) & 0x7 = 0x123 & 7 = 3 */
cfg = field_set(cfg, 4, 3, 5);           /* clears bits 6..4, writes 101 -> 0x1254 */

Why mask the new value too: & mask after shifting stops a too-large val from spilling into neighbouring fields. Writing 9 into a 3-bit field without it would corrupt bit 7.

Real registers: read-modify-write. On a peripheral register:

uint32_t v = PERIPH->CR;          /* read once */
v &= ~PSC_Msk;
v |= (psc << PSC_Pos) & PSC_Msk;
PERIPH->CR = v;                   /* write once */

Reading into a local and writing once avoids two separate bus writes that would put a half-updated value into the hardware in between.

Traps

  • width == 32: 1u << 32 is undefined; use GENMASK-style macros.
  • Do not use C bit-fields (struct { unsigned psc:3; }) for hardware registers: the bit order, padding and access width are implementation-defined, and the compiler may use byte accesses on a register that only accepts 32-bit accesses.

Linux: FIELD_GET(MASK, reg) and FIELD_PREP(MASK, val) from <linux/bitfield.h>, with GENMASK(h, l) for the mask. CMSIS headers give _Pos and _Msk macros for each field.