Bit-field Layout and External Data

suggest change

Bit-fields can give names to small integer fields within a structure:

struct encoder_position {
    unsigned encoder_counts : 23;
    unsigned encoder_turns : 4;
    unsigned reserved : 5;
};

This declaration does not define a portable 32-bit wire or hardware layout. The implementation determines the allocation order of bit-fields, whether fields cross allocation-unit boundaries, their alignment, and other layout details. Byte order is a separate concern and does not by itself determine bit-field order.

When decoding a hardware register, file, or network packet, read an integer of a specified width and extract fields with masks and shifts:

#include <stdint.h>

enum {
    COUNTS_BITS = 23,
    TURNS_BITS = 4,
};

static uint32_t encoder_counts(uint32_t word)
{
    return word & ((UINT32_C(1) << COUNTS_BITS) - 1);
}

static uint32_t encoder_turns(uint32_t word)
{
    return (word >> COUNTS_BITS)
           & ((UINT32_C(1) << TURNS_BITS) - 1);
}

Convert the external byte order to the host representation before applying these operations. This makes the format independent of the compiler's structure layout.

Bit-fields remain useful for compact implementation-local state when the exact object representation is not part of an external interface. See Bit-fields for their language rules.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents