C++ 使用 union 设置 64 位变量并读取 2 个 32 位

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]);

`

如果这是 set/get stored/read 在同一主机上(相同的字节顺序),你们是否看到任何问题

下面是更好的方法

`

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

};

`

方法很简单:

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

逆转(你没有明确要求但你的代码似乎暗示了)是这样的:

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

注意这里要先转换highword再移位