Array of bit fields in C

I have an 8 bit flag in C, and I want to access it by bit using bit fields like:

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

int main(void) {
    struct flags{
        uint8_t bits1:1;
        uint8_t bits2:1;
        uint8_t bits3:1;
        uint8_t bits4:1;
        uint8_t bits5:1;
        uint8_t bits6:1;
        uint8_t bits7:1;
        uint8_t bits8:1;
    };
    struct flags *my_flags;
    uint8_t x=6,i;

    my_flags=(struct flags *)&x;
    printf("%u\t",my_flags->bits5);
    printf("%u\t",my_flags->bits6);
    printf("%u\t",my_flags->bits7);
    printf("%u\t",my_flags->bits8);
    printf("%u\t",my_flags->bits1);
    printf("%u\t",my_flags->bits2);
    printf("%u\t",my_flags->bits3);
    printf("%u\t",my_flags->bits4);
    return 0;
}

and I get the expected result: 0 0 0 0 0 1 1 0.

But that is too much coding.

  • Is there something like an array of bit fields or any other workaround? (Or)
  • Is there something similar in C my_flags->bits_iwhere there iwill be a counter in a loop?

I know that in C there is no default. But are there alternatives to achieve the same?

+4
source share
2 answers

You can use union with anonymous internal structure (C11):

union flags
{
    unsigned char u;
    struct
    {
        uint8_t bits1:1;
        uint8_t bits2:1;
        uint8_t bits3:1;
        uint8_t bits4:1;
        uint8_t bits5:1;
        uint8_t bits6:1;
        uint8_t bits7:1;
        uint8_t bits8:1;
    };
};

What you can use, for example, as follows:

union flags x = {0x42};

for (i = CHAR_BIT - 1; i >= 0; i--)
{
    printf("%d\t", (x.u >> i) & 1);
}

printf("\n");

and to access a specific bit:

x.bits8 = 1;
printf("%d\n", x.bits8);

GNU C89 C99.

+8
  • .
  • , >> &

    int main() {
        int i, x=45;
        for(i=0; i<8; i++) {
            printf("%d", (x>>(7-i))&1);
        }
    }
    
+5

All Articles