Search code examples
c++structunionsbit-fields

Proper syntax for using union with bit fields inside a struct


I have the following series of structs.

struct FooWord1
{
    unsigned int Fill      :  8;
    unsigned int someData1 : 18;
    unsigned int someData2 : 6;
};

struct FooWord2
{
    unsigned int Fill      :  8;
    union
    {
        unsigned int A_Bit : 1;
        unsigned int B_Bit : 1;
    };
    unsigned int someData3 : 23;
};

struct Foo_Data
{
    FooWord1 fooWord1;
    FooWord2 fooWord2;
    FooWord3 fooWord3;  // similar to FooWord1
    FooWord4 fooWord4;  // similar to FooWord1
    FooWord5 fooWord5;  // similar to FooWord1
};

Foo_Data fooArray[SIZE];

Data gets copied into fooArray byte-by-byte from a network message. We get the data we expect in someData3 if we don't use a union with the 1-bit field (A_bit and B_bit), but as soon as we put in the union, the words get "off" by 2 words.

We want to use a union there because these structures are used for different types of messages, but the meaning of A_Bit and B_Bit is different for different messages. We could just use a comment, but it would be nice to do it in code.

What am I doing wrong?


Solution

  • The answer lies in the comments to the original question. Fill, the union, and someData3 will all wind up in separate words, because the union starts a new word in the struct.