c bit access union
A union in C allows multiple variables of different types to be stored in the same memory location. The size of a union is determined by the size of its largest member.
To access individual bits within a union, you can use bit-fields. Bit-fields allow you to specify the number of bits each member should occupy. Here's an example:
#include <stdio.h>
union Example {
int value;
struct {
unsigned int bit1 : 1;
unsigned int bit2 : 1;
unsigned int bit3 : 1;
unsigned int bit4 : 1;
};
};
int main() {
union Example example;
example.value = 10;
printf("bit1: %u\n", example.bit1);
printf("bit2: %u\n", example.bit2);
printf("bit3: %u\n", example.bit3);
printf("bit4: %u\n", example.bit4);
return 0;
}
In this example, we define a union called Example
. It has a member called value
of type int
and a nested struct containing four bit-fields, bit1
, bit2
, bit3
, and bit4
, each occupying 1 bit.
In the main()
function, we assign a value of 10 to example.value
. We can then access individual bits by using the bit-field names (example.bit1
, example.bit2
, etc.) and print their values.
Note: The order of the bit-fields within the struct is implementation-defined, so it's not guaranteed to be consistent across different compilers or platforms.