ABC of Electronics cosycom.com
EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 49

Structs, Unions and Bit-Fields

Giving structure to registers and messages.

A struct groups related values under one name, such as a sensor reading with a value, a time and a status. A union lets the same bytes be viewed in different ways, for example as one 16-bit number or as two bytes.

Bit-fields name individual bits in a byte. Their exact layout depends on the compiler, so use masks and shifts when the layout must be exactly right, such as in a message sent to another device.

Add the packed attribute only when you must match a wire format, since it can slow access.

EXAMPLE
typedef struct {
    int16_t  value;
    uint32_t time_s;
    uint8_t  ok;
} Reading;

typedef union {
    uint16_t word;
    uint8_t  bytes[2];
} Split;