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?
source
share