Page 66 - C-Language
P. 66
#include <stdio.h>
int main(void)
{
/* define a small bit-field that can hold values from 0 .. 7 */
struct
{
unsigned int uint3: 3;
} small;
/* extract the right 3 bits from a value */
unsigned int value = 255 - 2; /* Binary 11111101 */
small.uint3 = value; /* Binary 101 */
printf("%d", small.uint3);
/* This is in effect an infinite loop */
for (small.uint3 = 0; small.uint3 < 8; small.uint3++)
{
printf("%d\n", small.uint3);
}
return 0;
}
Bit-field alignment
Bit-fields give an ability to declare structure fields that are smaller than the character width. Bit-
fields are implemented with byte-level or word-level mask. The following example results in a
structure of 8 bytes.
struct C
{
short s; /* 2 bytes */
char c; /* 1 byte */
int bit1 : 1; /* 1 bit */
int nib : 4; /* 4 bits padded up to boundary of 8 bits. Thus 3 bits are padded */
int sept : 7; /* 7 Bits septet, padded up to boundary of 32 bits. */
};
The comments describe one possible layout, but because the standard says the alignment of the
addressable storage unit is unspecified, other layouts are also possible.
An unnamed bit-field may be of any size, but they can't be initialized or referenced.
A zero-width bit-field cannot be given a name and aligns the next field to the boundary defined by
the datatype of the bit-field. This is achieved by padding bits between the bit-fields.
The size of structure 'A' is 1 byte.
struct A
{
unsigned char c1 : 3;
unsigned char c2 : 4;
unsigned char c3 : 1;
};
https://riptutorial.com/ 42

