Bit Field Packing for Register Map

Medium C Configuration Asked at Renesas
Solve this problem

Peripheral configuration registers pack several fields into one word. Write pack and unpack helpers for a control register with a 3-bit mode, a 5-bit prescaler and an enable flag.

Constraints

  • Layout: bit 0 = enable, bits 3:1 = mode, bits 8:4 = prescaler, bits 31:9 reserved and must read back as 0.
  • `uint32_t ctrl_pack(int enable, int mode, int prescaler)`.
  • `void ctrl_unpack(uint32_t reg, int *enable, int *mode, int *prescaler)`.
  • Out-of-range field values must be masked, not rejected.
  • Do not use C bitfield structs - the layout must be explicit.
Starter codeC
1#include <stdint.h>2 3uint32_t ctrl_pack(int enable, int mode, int prescaler);4void ctrl_unpack(uint32_t reg, int *enable, int *mode, int *prescaler);