在 C++ 中将两个整数连接成一个更大的整数

Tor*_*oft 3 c++ integer

我需要两个单独的 16 位整数,它们可以一起形成一个 32 位整数。但每当我更改其中任何一个时,我都需要更新它们。假设我更改了 32 位的值,我需要将其自动写入两个 16 位的值,反之亦然。这可能吗?

Wan*_*nze 8

您可以使用代理类来表示 32 位整数:

class Proxy {
private:
    uint16_t &_high, &_low;

public:
    Proxy(uint16_t &high, uint16_t &low) : _high(high), _low(low) {}

    Proxy &operator=(uint32_t whole) {
        _high = whole >> 16;
        _low = whole & 0xffff;
        return *this;
    }

    operator uint32_t() const {
        return (_high << 16) | _low;
    }
};

int main() {
    uint16_t high = 0xa, low = 0xb;
    Proxy whole(high, low);
    std::cout << std::hex;
    std::cout << whole << '\n'; // a000b
    high = 0xc;
    low = 0xd;
    std::cout << whole << '\n'; // c000d
    whole = 0xe000f;
    std::cout << high << ' ' << low << '\n'; // e f
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

通过提供operator uint32_t,在大多数情况下Proxy可以隐式转换为uint32_t