How to create a union with a 32-bit int and four 8-bit char types that each refer to a difference piece of a 32-bit int?

I want to create a union in which the largest member is a 32-bit integer. This is what will be mostly written. Then there are four 8-bit variables, possibly char types, that will relate to another section of the 32-bit integer type:

union { int32 myint; char char1 [7:0]; char char2 [15:8]; char char3 [23:16]; char char4 [31:24]; } 

But I'm not sure how to do this in C ++.

+6
source share
4 answers

I did not understand if you want one 32bits interger AND 4 8bits or one 32bits interger to divide into 4 8 bits, but in any case you should try something like this:

 union yourUnion { int32 yourInt; struct { int32 var1 : 8; int32 var2 : 8; int32 var3 : 8; int32 var4 : 8; } yourSplitInterger; }; 

Hope this helps.

+4
source

This may work:

 union { int32 myint; char chars[4]; }; 
+5
source

You can use this:

 union myUnion { int32 myint; struct { char char1; char char2; char char3; char char4; } myChars; }; 

or with uint8_t :

 union myUnion { uint32_t myint; struct { uint8_t b1; uint8_t b2; uint8_t b3; uint8_t b4; // or number them in reverse order } myBytes; }; 

See here .

+3
source
 union intBytes { int32 myInt; struct { char char1; char char2; char char3; char char4; }; char charArray[4]; }; intBytes dummy; 

You can see that no name is assigned to wrap the char1 - char4 structure. This is called anonymous struct . Members of an anonymous structure are directly accessible within the area surrounded by the structure.

Without struct char1 - char4 will overlap inside the union, and everyone will refer to the first byte of myInt . An anonymous structure ensures that char1 - char will be executed sequentially.

C has anonymous structures and associations. C ++ (pre C ++ 11) DOES NOT allow anonymous structures; only anonymous associations are defined. However, most C ++ compilers (llvm, gcc) allow anonymous structure / associations.

Anonymous structures have been added in C ++ in C ++ 11.

This allows you to access dummy.char4 , while normally you will need to enter dummy.nameOfCharStruct.char4 . Since this is not a standard C ++ correspondence (I believe that it was changed in post C ++ 03 Standatd), you might be better off adding a structure name or using an array approach.

+2
source

All Articles