Page 68 - C-Language
P. 68
that is greater than, or equal to, the size of the structure. Then the entire set of bit-fields may be
zeroed by zeroing this unsigned integer.
typedef union {
struct {
unsigned int a:2;
unsigned int b:1;
unsigned int c:3;
unsigned int d:1;
unsigned int e:1;
};
uint8_t data;
} union_bit;
Usage is as follows
int main(void)
{
union_bit un_bit;
un_bit.data = 0x00; // clear the whole bit-field
un_bit.a = 2; // write into element a
printf ("%d",un_bit.a); // read from element a.
return 0;
}
In conclusion, bit-fields are commonly used in memory constrained situations where you have a lot
of variables which can take on limited ranges.
Don'ts for bit-fields
1. Arrays of bit-fields, pointers to bit-fields and functions returning bit-fields are not allowed.
2. The address operator (&) cannot be applied to bit-field members.
3. The data type of a bit-field must be wide enough to contain the size of the field.
4. The sizeof() operator cannot be applied to a bit-field.
5. There is no way to create a typedef for a bit-field in isolation (though you can certainly create
a typedef for a structure containing bit-fields).
typedef struct mybitfield
{
unsigned char c1 : 20; /* incorrect, see point 3 */
unsigned char c2 : 4; /* correct */
unsigned char c3 : 1;
unsigned int x[10]: 5; /* incorrect, see point 1 */
} A;
int SomeFunction(void)
{
// Somewhere in the code
A a = { … };
printf("Address of a.c2 is %p\n", &a.c2); /* incorrect, see point 2 */
printf("Size of a.c2 is %zu\n", sizeof(a.c2)); /* incorrect, see point 4 */
}
Read Bit-fields online: https://riptutorial.com/c/topic/1930/bit-fields
https://riptutorial.com/ 44

