Parse a hardware status register into named fields.
#include <stdint.h>
#include <stdbool.h>
/* example: bit 0 READY, bit 1 ERROR, bits 4..6 MODE, bits 8..15 FIFO level */
#define ST_READY (1u << 0)
#define ST_ERROR (1u << 1)
#define ST_MODE_Pos 4u
#define ST_MODE_Msk (7u << ST_MODE_Pos)
#define ST_FIFO_Pos 8u
#define ST_FIFO_Msk (0xFFu << ST_FIFO_Pos)
#define FIELD_GET(reg, f) (((reg) & f##_Msk) >> f##_Pos)
typedef struct { bool ready, error; uint8_t mode, fifo_level; } status_t;
status_t parse_status(uint32_t reg) /* read the register ONCE, then decode the copy */
{
status_t s;
s.ready = (reg & ST_READY) != 0;
s.error = (reg & ST_ERROR) != 0;
s.mode = (uint8_t)FIELD_GET(reg, ST_MODE);
s.fifo_level = (uint8_t)FIELD_GET(reg, ST_FIFO);
return s;
}
/* parse_status(0x00002353) -> ready 1, error 1, mode 5, fifo 0x23 */
Points: read the register once into a local (re-reading may give inconsistent fields, and some status bits clear on read); decode with mask-then-shift; define each field once with _Pos/_Msk macros; check reserved bits are ignored. To clear write-1-to-clear flags afterwards, write only the bits you handled.