Bit Manipulation

Article · 1:00

Bit fields, masking, and the register-style operations C exists for.

Working on individual bits is ordinary in C, because C is what talks to hardware. The four operations to know are set (x |= mask), clear (x &= ~mask), toggle (x ^= mask) and test (x & mask). Build each mask with a shift - 1u << n - rather than writing a literal, because the shift says which bit you mean.

Packing several booleans into one integer is the common use: eight flags in one byte rather than eight bytes, which matters in a protocol header or an embedded device with kilobytes of RAM.

A bit field lets you declare the widths inside a struct - unsigned int ready : 1; - and the compiler does the masking. It is readable, and it is not portable: the standard does not fix the order the bits are laid out in, so a bit field struct overlaid on a real hardware register may work on one compiler and not the next. For hardware, explicit masks and shifts are safer.

Two cautions. Always shift unsigned types: right-shifting a negative signed value is implementation-defined, and left-shifting into the sign bit is undefined behaviour. And shifting by more than the width of the type - 1u << 32 on a 32-bit unsigned - is undefined, not zero, which is a real bug in loops that build masks.

#include <stdio.h>
#include <stdint.h>

#define FLAG_READY   (1u << 0)
#define FLAG_ERROR   (1u << 1)
#define FLAG_BUSY    (1u << 2)

/* Readable, and NOT portable: the standard does not fix bit order, so
   this is fine for your own packing and risky over a real register. */
struct Status {
    unsigned int ready : 1;
    unsigned int error : 1;
    unsigned int code  : 6;     /* 0 to 63 */
};

int main(void)
{
    uint8_t flags = 0;

    flags |=  FLAG_READY | FLAG_BUSY;   /* set    */
    flags &= ~FLAG_BUSY;                /* clear  */
    flags ^=  FLAG_ERROR;               /* toggle */

    if (flags & FLAG_READY) printf("ready\n");      /* test */

    /* Print the bits, high to low. */
    for (int bit = 7; bit >= 0; bit--)
        putchar((flags & (1u << bit)) ? '1' : '0');
    putchar('\n');

    /* Packing two 4-bit values into one byte. */
    uint8_t high = 0xA, low = 0x5;
    uint8_t packed = (uint8_t) ((high << 4) | low);
    printf("packed 0x%02X -> high %X low %X\n",
           packed, (packed >> 4) & 0xF, packed & 0xF);

    struct Status st = { .ready = 1, .error = 0, .code = 42 };
    printf("ready %u code %u, struct is %zu bytes\n",
           st.ready, st.code, sizeof st);

    /* Undefined, not zero: shifting by the width of the type. And
       always shift UNSIGNED - a negative right shift is
       implementation-defined. */
    /* unsigned u = 1u << 32; */
    return 0;
}