Home / Learn Chip Programming / Structs, Unions, Bitfields and Alignment

Structs, Unions, Bitfields and Alignment

Describe registers and protocol frames as structs, and understand padding.

In shortDescribe registers and protocol frames as structs, and understand padding.

Theory in plain words

Struct layoutuint8_t apadding 3 bytesuint32_t bsizeof = 8
Struct layout

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

See padding and sizeTry it Yourself

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.

Register block and bitfield
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;
Tip:For portable register code prefer masks and shifts over bitfields: the bit order inside a bitfield is compiler defined.

Quick quiz

1. Why does a struct have padding?

2. A union is used to...