Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

unions

I want to create a union in which the biggest member is a 32 bit integer. This is what will be mainly written to. Then there are four 8 bit variables, probably char types that will each refer to a different section of the 32 bit integer kind of like:

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

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

like image 804
quantum231 Avatar asked Jan 11 '16 22:01

quantum231


3 Answers

This may work:

union {
   int32 myint;
   char chars[4];
};
like image 64
Cecilio Pardo Avatar answered Nov 15 '22 23:11

Cecilio Pardo


I didn't understand if you wanted one 32bits interger AND 4 8bits variables or one 32bits interger split in 4 8bits variables, but anyway 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 it helps.

like image 39
Maxattak Avatar answered Nov 15 '22 23:11

Maxattak


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.

like image 24
Danny_ds Avatar answered Nov 15 '22 22:11

Danny_ds