In C Programming Language we have the option to store integer members into memory spaces smaller than the compiler would ordinarily allow. These can be achieved using the space-saving structure members are called bit fields, and their width in bits can be explicitly declared.
This is very useful especially when memory or data storage is at a premium. A bit field is set up with a structure declaration that labels each field and determines its width.
Bit Field Declaration
1 2 3 4 |
struct { type [member_name] : width ; }; |
A bit-field declaration contains a type specifier followed by an optional member_name, a colon, a constant integer expression that indicates the field width in bits, and a semicolon.
Bit fields with a width of 0 must be unnamed. Unnamed bit-fields cannot be referenced or initialized. If a series of bit fields do not makeup up the size of an int, padding can take place.
The following example demonstrates padding. Suppose that an int occupies 4 bytes. The example declares the identifier room to be of type struct app_state:
1 2 3 4 5 6 7 8 9 10 |
struct app_state{ unsigned light : 1; unsigned fan: 1; int count; /* 4 bytes */ unsigned ac : 4; unsigned : 4; unsigned clock : 1; unsigned : 0; unsigned flag : 1; } room; |
The structure room contains eight members with a width of 16 bytes. The following table describes the storage that each member occupies:
Member Name | Storage Occupied |
---|---|
light | 1 bit |
fan | 1 bit |
(padding — 30 bits) | To the next int boundary |
count | The size of an int (4 bytes) |
ac | 4 bits |
(unnamed field) | 4 bits |
clock | 1 bit |
(padding — 23 bits) | To the next int boundary (unnamed field) |
flag | 1 bit |
(padding — 31 bits) | To the next int boundary |
You can not access the field by direct its name.
Syntax:
1 |
structure_var.member; |
We can access the member “light” as “room. light”, The following expression sets the light field to 1
1 |
room.light = 1; |
When you assign to a bit field a value that is out of its range, the bit pattern is preserved and the appropriate bits are assigned. The following expression sets the “fan” field of the room structure to a 0 (zero) because only the least significant bit is assigned to the fan field:
1 |
room.fan= 2; |
Note:- The maximum bit field length is 64 bits. For portability, do not use bit fields greater than 32 bits in size.