user1128797
user1128797

Reputation: 21

Could this union give unexpected values on a little endian machine

Could this union give me problem on a little endian machine

union {
    struct {  
        uint32_t min[4];        
        uint32_t max[4];        
    } x1;

    struct {  
        uint64_t min[2];       
        uint64_t max[2];       
    } x1_64;
} u;

If i store values using struct x1 and retrieve using x1_64 would the endianness come into play and return unexpected values??

Upvotes: 0

Views: 58

Answers (2)

marom
marom

Reputation: 5230

On a little-endian machine ((unsigned char *)u.min[0] will point to the least significant byte of both u.min values and u.min[0] (of type uint32_t) will contain the lowest 32 bits of the 64 value.

On a big-endian machine ((unsigned char *)u.min[0]) will contain the most significant byte of both u.min values and u.min[0] will contain the highest 32 bits.

So endianness matters as usual.

Upvotes: 1

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

I think the answer is "yes". On a little endian machine you have to store x1 in reverse order. See the following picture:

enter image description here

It means that the low part of x1_64.min[0] should be stored as x.min[1] and the high part as x1.min[0]. On a big endian machine you do not have to do this.

(n.b.: I'm always confused with little and big, so excuse me if it should read "big endian")

Upvotes: 1

Related Questions