Why must butfields sum to a multiple of a byte?

Andrej Mitrovic andrej.mitrovich at gmail.com
Mon Jul 30 07:19:45 PDT 2012


It says for std.bitmanip.bitfields:

"The sum of all bit lengths in one bitfield instantiation must be
exactly 8, 16, 32, or 64."
It has a static assert to verify this. But why does this limitation exist?

I was thinking of cases where I'm wrapping a C++ POD struct which has
bitfields and is packed on a 1-byte boundary. GCC example:

#include <stdio.h>
#pragma pack(1)
struct Foo
{
    unsigned int bits1 : 1;
    unsigned int bits2 : 2;
};

int main()
{
    printf("%d\n", sizeof(Foo));
    return 0;
}

I can't translate this to D using the bitfields mixin since it
requires a multiple of a byte, 3 bits isn't a byte:

import std.stdio;
import std.bitmanip;

align(1) struct Foo
{
    mixin(bitfields!(
        uint, "bits1", 1,
        uint, "bits2", 2
    ));
}

void main() { writeln(Foo.sizeof); }

std\bitmanip.d(151): Error: static assert  "Field widths must sum to
8, 16, 32, or 64"

Is this a language limitation? I guess because 'byte' is the smallest
legal type in D this is what the bitfields mixin uses internally?


More information about the Digitalmars-d-learn mailing list