C++ Bit Fields

C++ allows you to pack bit fields. This isn’t something I’ve used as it seems to have some very specific use cases and is platform dependent (also see bit field notes).

Individual class or struct data members can be given an explicit bit size (as per the cppreference examples):

struct S {
 // three-bit unsigned field therefore allowed values are 0...7
 unsigned int b : 3;

Similarly, this can be extended to more than one data member:

struct S {
    // will usually occupy 2 bytes:
    // 3 bits: value of b1
    // 2 bits: unused
    // 6 bits: value of b2
    // 2 bits: value of b3
    // 3 bits: unused
    unsigned char b1 : 3, : 2, b2 : 6, b3 : 2;

A C++ bitset isn’t the same thing:

The class template bitset represents a fixed-size sequence of N bits. Bitsets can be manipulated by standard logic operators and converted to and from strings and integers.

One reason for using bit fields is to efficiently pack data into the smallest space possible, another is to construct data at some physical interface layer, for example, writing an IP packet header. To access the data members the compiler would have to generate instructions that mask and shift values, so using bit-fields isn’t necessarily efficient.

© 2018