Home / Learn Chip Programming / Structs, Unions, Bitfields and Alignment
Structs, Unions, Bitfields and Alignment
Describe registers and protocol frames as structs, and understand padding.
Theory in plain words
What it is
A struct groups fields; a union overlays them; a bitfield names bits. The compiler may insert padding to align fields.
Why we use it
Peripheral register blocks (CMSIS) are structs. Packets are structs or unions. Alignment mistakes break communication.
How it works
Order fields largest first or use __attribute__((packed)) when matching wire formats. Do not rely on bitfield order across compilers for hardware portability.
Where it is used
- CMSIS register definitions
- Network and radio frames
- Config records saved in flash
Layout calculator
Padding wastes RAM and changes the wire format. Packed structs match a protocol but can be slower or fault on unaligned access on some cores.
typedef struct {
volatile uint32_t MODER; // offset 0x00
volatile uint32_t OTYPER; // 0x04
volatile uint32_t OSPEEDR; // 0x08
volatile uint32_t IDR; // 0x10 ...
} GPIO_TypeDef;
#define GPIOA ((GPIO_TypeDef *)0x48000000)
GPIOA->MODER |= (1u << 10); // pin 5 output
typedef union { uint8_t raw; struct { uint8_t en:1, mode:2, level:5; } f; } cfg_t;Quick quiz
1. Why does a struct have padding?
CPUs prefer aligned access.
2. A union is used to...
Fields share storage.