Page 67 - C-Language
P. 67
In structure B, the first unnamed bit-field skips 2 bits; the zero width bit-field after c2 causes c3 to
start from the char boundary (so 3 bits are skipped between c2 and c3. There are 3 padding bits
after c4. Thus the size of the structure is 2 bytes.
struct B
{
unsigned char c1 : 1;
unsigned char : 2; /* Skips 2 bits in the layout */
unsigned char c2 : 2;
unsigned char : 0; /* Causes padding up to next container boundary */
unsigned char c3 : 4;
unsigned char c4 : 1;
};
When are bit-fields useful?
A bit-field is used to club together many variables into one object, similar to a structure. This
allows for reduced memory usage and is especially useful in an embedded environment.
e.g. consider the following variables having the ranges as given below.
a --> range 0 - 3
b --> range 0 - 1
c --> range 0 - 7
d --> range 0 - 1
e --> range 0 - 1
If we declare these variables separately, then each has to be at least an 8-bit integer and the total
space required will be 5 bytes. Moreover the variables will not use the entire range of an 8 bit
unsigned integer (0-255). Here we can use bit-fields.
typedef struct {
unsigned int a:2;
unsigned int b:1;
unsigned int c:3;
unsigned int d:1;
unsigned int e:1;
} bit_a;
The bit-fields in the structure are accessed the same as any other structure. The programmer
needs to take care that the variables are written in range. If out of range the behaviour is
undefined.
int main(void)
{
bit_a bita_var;
bita_var.a = 2; // to write into element a
printf ("%d",bita_var.a); // to read from element a.
return 0;
}
Often the programmer wants to zero the set of bit-fields. This can be done element by element,
but there is second method. Simply create a union of the structure above with an unsigned type
https://riptutorial.com/ 43

