Search code examples
c++structunions

C++ using union to set 64bit variable and read 2 32bits


`

union {
    uint64_t    entryid;
    uint32_t    entryid[2];
};

entryid = get64bitKey();

storeKeytodb(entryid[0],entryid[1]);
.........
getKeyFromDB(&entrid[0], &entryid[1]);

`

Do you guys see any issue with this if this is set/get stored/read on same host (same endianness)

Is below a better way of doing this

`

union {
    uint64_t    entryid;
    struct {
    uint32_t    entryid1;
    uint32_t    entryid2;
    }entry;

};

`


Solution

  • The way to do that is simply this:

    uint64_t value = ...
    uint32_t highword = static_cast<uint32_t>(value >> 32);
    uint32_t lowword = static_cast<uint32_t>(value);
    

    The revers (which you didn't explicitly ask for but which your code seems to suggest) is this:

    uint32_t highword = ...
    uint32_t lowword = ...
    uint64_t value = (static_cast<uint64_t>(highword) << 32) + lowword;
    

    Note that here, it is important to first convert the highword and then to shift it.