The correct syntax for using union with bit fields within a structure

I have the following series of structures.

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 is copied to fooArray bytes from the network message. We get the data expected in someData3 if we do not use a union with a 1-bit field ( A_bit and B_bit ), but as soon as we enter a union, the words "off" into 2 words.

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

What am I doing wrong?

+6
source share
2 answers

The answer lies in the comments on the original question. Fill , union and someData3 will end in separate words, because union starts a new word in the structure.

0
source

You can try the following:

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

It is worth mentioning: according to this answer, anonymous structures are not a C ++ standard, but an extension. GCC, MSVC permissions - as far as I remember. too. LLVM? Not sure, but, as often close to GCC, that will also be so.

In standard matching libraries, they use macros to get the correct effect, for example:

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

Just explanatory: with your source code, you got this effect:

  • Fills a new bit field
  • union is a different data type, so the previous bit field is completed
  • Inside the union, a new bit field begins. I am not sure if this creates a single bit or perhaps a bit field with two entries. Perhaps someone can shed light on what the standard state is ...
  • Closing the union, bit-bit is also complete.
  • someData3 then launches a new bit field

Thus, the bias you want to avoid.

0
source

All Articles