Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a union right aligned in C?

For example,the default alignment of a union is following:

union{
   uint32_t v4;
   __uint128_t v6;
}ip;

//in memory
//aaaa
//bbbbbbbbbbbbbbbb

But I want to have a union right aligned:

//            aaaa
//bbbbbbbbbbbbbbbb

Is it possible to achieve this in C?

like image 235
Sam Chiu Avatar asked Jan 24 '23 09:01

Sam Chiu


1 Answers

You can use a C11 anonymous struct for this.

union {
#pragma pack(1)
    struct {
        char padding_[sizeof(__uint128_t) - sizeof(uint32_t)];
        uint32_t v4;
    };
#pragma pack(0)
    __uint128_t v6;
} ip;

// usage
ip.v4 = 0x7F000000;
like image 51
Ray Hamel Avatar answered Jan 29 '23 14:01

Ray Hamel