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.
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?
Arrays of bit fields, pointers to bit fields, and functions returning bit fields are not allowed. The optional declarator names the bit field. Bit fields can only be declared as part of a structure. The address-of operator (&) cannot be applied to bit-field components.
A bit array is an array data structure that compactly stores bits. It can be used to implement a simple set data structure. A bit array is effective at exploiting bit-level parallelism in hardware to perform operations quickly.
Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared.
No, you can't. Bit field can only be used with integral type variables.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With