C++ bit fields

C++ Bit Fields
Visual Studio 2005Other Versions Visual Studio 2010Visual Studio 2008Visual Studio .NET 2003

Classes and structures can contain members that occupy less storage than an integral type. These members are specified as bit fields. The syntax for bit-field member-declarator specification follows:

Copy
declarator : constant-expression
Remarks
--------------------------------------------------------------------------------

The (optional) declarator is the name by which the member is accessed in the program. It must be an integral type (including enumerated types). The constant-expression specifies the number of bits the member occupies in the structure. Anonymous bit fields — that is, bit-field members with no identifier — can be used for padding.

Note
An unnamed bit field of width 0 forces alignment of the next bit field to the next type boundary, where type is the type of the member.


The following example declares a structure that contains bit fields:

Copy// bit_fields1.cpp
// compile with: /LD
struct Date {
unsigned short nWeekDay : 3; // 0..7 (3 bits)
unsigned short nMonthDay : 6; // 0..31 (6 bits)
unsigned short nMonth : 5; // 0..12 (5 bits)
unsigned short nYear : 8; // 0..100 (8 bits)
};
The conceptual memory layout of an object of type Date is shown in the following figure.


Memory Layout of Date Object





Note that nYear is 8 bits long and would overflow the word boundary of the declared type, unsigned short. Therefore, it is begun at the beginning of a new unsigned short. It is not necessary that all bit fields fit in one object of the underlying type; new units of storage are allocated, according to the number of bits requested in the declaration.

No comments:

Post a Comment