Bit Fields

Bit fields provide a syntax for masking individual bits within an integral type. A member whose declarator is of the form:

identifier : constant_expression

is interpreted as a bit field. The constant expression specifies the length of the bit field. Bit fields are highly implementation dependent. The following is true of bit fields.


Following is an example of the use of bit fields.

#include <iostream.h>
class test        // This class consists of 4 bytes
  int b1 : 8;     // Each bit field is a byte.
  int b2 : 8;     // On 32 bit Intel an integer is 4 bytes.
  int b3 : 8;     // All supported compilers allocate
  int b4 : 8;     // these bit fields in the same manner.
void main()
 test instance;       // Declare an instance of test
 instance.b1 = 0xaa;  // Assign to each of the bit fields
 instance.b2 = 0xbb;
 instance.b3 = 0xcc;
 instance.b4 = 0xdd;
 int* pi = (int*)&instance;  // pi points to the instance's memory
 cout.setf(ios::hex,ios::basefield); // set output stream to print in hex
 cout << (int)*pi;                   // print out the structure's memory.

For the supported compilers, the following is printed out: ddccbbaa.