enricorossi.org

Enrico Rossi


Union struct and bitfield in C

Published:
Last updated:
By Enrico Rossi
Category: howto
Tags: C, howto, tips

please see updated version: union struct bitfield and endianess in C

Typical usage of a bitfield with struct and union in C

/*
 * Copyright © 2016 Enrico Rossi <e.rossi@tecnobrain.com>
 *
 * This work is free. You can redistribute it and/or modify it under the
 * terms of the Do What The Fuck You Want To Public License, Version 2,
 * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
 */

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

union status_t {
    struct {
        uint8_t b7:1;
        uint8_t b6:1;
        uint8_t b5:1;
        uint8_t b4:1;
        uint8_t b3:1;
        uint8_t b2:1;
        uint8_t b1:1;
        uint8_t b0:1;
    } bits;

    uint8_t byte;
};

int main(void)
{
    union status_t status;
    int i;

    printf("The size of the union is: %01x byte.\n", sizeof(status));

    for (i=0; i<8; i++) {
        status.byte = (1<<i);
        printf("Setting bit %d: %01x%01x%01x%01x%01x%01x%01x%01x\n", i,
                status.bits.b0, status.bits.b1, status.bits.b2, status.bits.b3,
                status.bits.b4, status.bits.b5, status.bits.b6, status.bits.b7);
    }

    return(0);
}