Bit fields are probably one of the least popular language features of C/C++. By using bit fields the programmer can precisely define how many bits are occupied by each member of a struct
or class
. The syntax for bit fields follows:
struct Time { unsigned int pm : 1; unsigned int hour : 4; unsigned int minute : 6; };
The member field called pm
of the struct Time
above occupies only 1-bit, hour
occupies 4-bits and minute
occupies 6-bits.
Note that the members specified as a bit-field are always treated as integers, so you can omit the keyword int
from the definition as follows:
struct Time { unsigned pm : 1; unsigned hour : 4; unsigned minute : 6; };
Bit fields are accessed just as any other member:
int main() { Time time; time.pm = true; time.hour = 10; time.minute = 22; printf("The time is %d:%d %sn", time.hour, time.minute, time.pm ? "PM" : "AM"); return 0; }
Bit fields are actually useful for:
- Packing several objects into one or more bytes, hence precise control over memory occupation in terms of bits
- Creating structs suitable for reading data from, ans possibly writing data to, external file formats as well as transmitting data over network connections
Although it is unlikely that you would need to use bit fields in your program, if you ever do so make sure you pay attention to the following:
- Portability issues
- Thread-synchronization issues
I will not go into the details here. If you would like to know more about bit fields check following links:
msdn:??C Bit Fields
msdn: C++ Bit Fields
Wikipedia: Bit field