RatDon
RatDon

Reputation: 3543

Array of Bit_fields in C

I've a flag of 8 bits in C and I want to access it bit by bit using bit-fields like this:

#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 output: 0 0 0 0 0 1 1 0.

But this is a bit too much coding.

  1. Isn't there something like array of bit-fields or any other workaround for it? (or)
  2. Is there anything like this in C my_flags->bits_i where i will be a counter in a loop?

I know both are not there in C by default. But are there any alternatives to achieve the same?

Upvotes: 9

Views: 3730

Answers (2)

Rakesh Malik
Rakesh Malik

Reputation: 689

  1. No. You can't create an array of bit-field
  2. You can extract each bit by using >> and &

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

Upvotes: 6

ouah
ouah

Reputation: 145829

You can use an union with an anonymous inner 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;
    };
};

That you can use for example this way:

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);

An anonymous inner structure is also allowed as GNU extension to C89 and C99.

Upvotes: 15

Related Questions