Simvik

Overlay a register with bit-fields

Describe an 8-bit control register with a union of a byte and bit-fields. A medium embedded C problem (Structs, unions and memory layout), run and graded in…

medium · Structs, unions and memory layout · bit-fields · unions

A control register has this layout, from bit 0 upwards:

  • bit 0: enable
  • bits 3..1: mode
  • bits 5..4: prescaler
  • bit 6: reserved
  • bit 7: irq

Complete ctrl_reg_t so that bits.enable, bits.mode, bits.prescaler and bits.irq access those fields and raw accesses the whole byte.

Starter code

typedef union {
  uint8_t raw;
  struct {
    uint8_t enable : 1;   // bit 0
    // mode: bits 3..1, prescaler: bits 5..4, bit 6 reserved, irq: bit 7
  } bits;
} ctrl_reg_t;

Example tests

Writing fields changes the raw byte

ctrl_reg_t r = { .raw = 0 };
r.bits.enable = 1;
r.bits.mode = 5;
printf("0x%02X\n", r.raw);

Expected output:

0x0B

Reading fields from a raw byte

ctrl_reg_t r = { .raw = 0xA5 };
printf("%u %u %u %u\n", r.bits.enable, r.bits.mode, r.bits.prescaler, r.bits.irq);

Expected output:

1 2 2 1

Learn it first

More Structs, unions and memory layout problems