bitfields

Allows creating bit fields inside structs and classes.

The type of a bit field can be any integral type or enumerated type. The most efficient type to store in bitfields is bool, followed by unsigned types, followed by signed types.

template bitfields (
T...
) {}

Examples

Create a bitfield pack of eight bits, which fit in one ubyte. The bitfields are allocated starting from the least significant bit, i.e. x occupies the two least significant bits of the bitfields storage.

1 struct A
2 {
3     int a;
4     mixin(bitfields!(
5         uint, "x",    2,
6         int,  "y",    3,
7         uint, "z",    2,
8         bool, "flag", 1));
9 }
10 
11 A obj;
12 obj.x = 2;
13 obj.z = obj.x;
14 
15 assert(obj.x == 2);
16 assert(obj.y == 0);
17 assert(obj.z == 2);
18 assert(obj.flag == false);

The sum of all bit lengths in one bitfield instantiation must be exactly 8, 16, 32, or 64. If padding is needed, just allocate one bitfield with an empty name.

struct A
{
    mixin(bitfields!(
        bool, "flag1",    1,
        bool, "flag2",    1,
        uint, "",         6));
}

A a;
assert(a.flag1 == 0);
a.flag1 = 1;
assert(a.flag1 == 1);
a.flag1 = 0;
assert(a.flag1 == 0);

enums can be used too

enum ABC { A, B, C }
struct EnumTest
{
    mixin(bitfields!(
              ABC, "x", 2,
              bool, "y", 1,
              ubyte, "z", 5));
}

See Also

Meta

Suggestion Box / Bug Report