Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Embedded C

Structs, Unions, Bit-Fields and Endianness

Model registers and protocol packets in C: struct padding and alignment, packed structs, unions for type punning, bit-field pitfalls and little vs big endian.

Firmware constantly deals with data laid out by someone else: a peripheral's register block, a sensor's 6-byte response, a packet on a CAN bus, a header in flash. C's aggregate types (struct, union, bit-fields) let you describe those layouts, but the compiler has freedom you must understand: it may insert padding, it chooses the bit order inside bit-fields, and the CPU may store multi-byte numbers in either byte order.

This lesson shows how to measure and control layout, when to use unions, why bit-fields are risky for portable code, and how to detect and convert endianness.

Struct layout, alignment and padding

Many CPUs require (or are much faster at) accessing a uint32_t at an address divisible by 4. The compiler therefore aligns each member to its natural boundary and pads between members, and pads the end so that arrays of the struct stay aligned. Member order changes the size.

C
struct A { uint8_t a; uint32_t b; uint8_t c; };   // 12 bytes: 1 +3 pad +4 +1 +3 pad
struct B { uint32_t b; uint8_t a; uint8_t c; };   //  8 bytes: 4 +1 +1 +2 pad
C Padding and member order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rules of thumb: sort members from largest to smallest to minimize padding; use offsetof and sizeof (not guesses) when a layout matters; and be careful about sending a struct as raw bytes between systems, because the padding and the byte order may differ.

Packed structs and unaligned access

When you must match an external layout exactly (a file format, a wire protocol), you can tell the compiler to drop the padding: __attribute__((packed)) in GCC/Clang, #pragma pack(1) in several compilers.

C
struct __attribute__((packed)) Header {
    uint8_t  type;
    uint16_t length;      // now at offset 1: unaligned!
    uint32_t timestamp;
};                          // sizeof == 7

The cost: members can be unaligned. Cortex-M3 and up tolerate unaligned loads of 16/32 bits (slower), Cortex-M0 does not (a hard fault), and some chips silently read the wrong data. Never take the address of a packed member and pass it around as a plain uint32_t *. Safer alternatives: copy fields with memcpy into properly aligned locals, or build and parse buffers byte by byte.

C Packed vs padded, and a memcpy parse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The byte-wise form at the end is the most portable: it never depends on padding, alignment or the host's byte order.

Unions

A union stores all its members at the same address; its size is the size of the largest member. Writing one member and reading another reinterprets the same bytes. Embedded code uses unions to view a register as a whole word or as individual bytes or fields, and to convert a float to raw bits for transmission.

C
typedef union {
    uint32_t word;
    uint8_t  bytes[4];
    struct { uint16_t low; uint16_t high; } half;
} Reg32;

Reading a different member than the one last written is allowed in C (type punning through a union is defined in C99 and later, unlike C++), but the result is representation-dependent: byte order and padding decide what you see. The strictly portable way to reinterpret bits is memcpy.

C One register, three views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Endianness

A 32-bit value 0x11223344 occupies four bytes. Little-endian machines (x86, ARM Cortex-M in practice, RISC-V) store the least significant byte at the lowest address: 44 33 22 11. Big-endian machines (older PowerPC/SPARC, and the byte order of most network protocols, "network byte order") store 11 22 33 44.

You meet this whenever you send multi-byte values over a bus, store them in files, or read a sensor register pair. A temperature sensor may output the high byte first (big-endian); your CPU wants little-endian. The rule: define the byte order of every external format, and convert explicitly.

C Detect byte order and swap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Compilers offer helpers such as __builtin_bswap32, and libraries provide htons/ntohl. Writing bytes explicitly with shifts, as in the sensor example, works everywhere.

Bit-fields

C lets you declare members with a width in bits:

C
struct Control {
    uint32_t enable   : 1;
    uint32_t mode     : 2;
    uint32_t prescale : 3;
    uint32_t          : 2;     // unnamed padding
    uint32_t irq_en   : 1;
};

It reads nicely and many vendor headers use it. But the standard leaves critical details implementation-defined: whether the first field is the most or least significant bit, whether fields may straddle a storage unit, the signedness of plain int fields and how access is generated (a one-bit write can become a read-modify-write of a wider unit or even of neighboring bytes). A write to a bit-field of a hardware register may therefore produce an access of the wrong width.

Practical guidance:

  • Bit-fields are acceptable for fields that stay inside one program (flags, small state) when you do not care about the exact layout.
  • For registers and wire formats, prefer explicit masks and shifts. They make the access width and the layout visible and portable (see Bit Manipulation for Registers).
  • If you use bit-fields for registers, only with the vendor's documented compiler and always with volatile and uint32_t base types.
  • Never take the address of a bit-field.
C Bit-fields: size and portability check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

On GCC for little-endian targets the two agree, because GCC allocates bit-fields from the least significant bit upward. Another compiler or a big-endian target may disagree, which is exactly why the explicit version is preferred for hardware.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can reordering the members of a struct change its sizeof?

    Each member is aligned to its natural boundary, so large-to-small order usually wastes the least space.
  2. 2. Which is the safest way to parse a 32-bit little-endian value from a byte buffer?

    The shift form has no alignment or endianness assumptions. The cast can fault on unaligned addresses and breaks aliasing rules.
  3. 3. A little-endian CPU stores 0x11223344 at address 0x100. What is at address 0x100?

    Little-endian stores the least significant byte first, at the lowest address.
  4. 4. Why are bit-fields discouraged for describing hardware registers?

    The standard does not fix the layout, so the same declaration can behave differently across compilers and targets.

Summary

  • Structs are padded for alignment; use sizeof/offsetof, order members large to small, and avoid sending raw structs between systems.
  • Packed structs remove padding but create unaligned members; copy with memcpy or parse bytes.
  • Unions view the same bytes in several ways; memcpy is the strictly portable way to reinterpret bits.
  • Endianness decides which byte comes first; convert explicitly with shifts or swap helpers.
  • Prefer explicit masks and shifts over bit-fields for registers and wire formats.

Next: Macros, Inline Functions and Compile-Time Checks