Hex Editor - Binary File Editing Software for Windows
Download Hex Editor Neo Hide this button

Bit Field

Bit field is an integer field which occupies less space than the underlying integer type.

Syntax:

typeid var-id:expression;

The underlying type-id of a bit field must be an integer type. Expression may be constant expression or dynamic expression.

Example of bit fields:

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.

Bit Fields

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.

The ordering of data declared as bit fields is from low to high bit, as shown in the figure above.