Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining two integers into one bigger integer in C++

Tags:

c++

integer

I need to have two separate 16-bit integers, that can form a 32-bit integer together. But I need them to be updated whenever I change any of them. Let's say I change the value of the 32-bit, I need it to be automatically written over the two 16-bit ones and vice versa. Is this possible?

like image 330
Torisoft Avatar asked Jan 25 '26 14:01

Torisoft


1 Answers

You can use a proxy class to represent your 32-bit integer:

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;
}

By providing operator uint32_t, Proxy can be implicitly converted to uint32_t in most cases.

like image 115
wtz Avatar answered Jan 27 '26 04:01

wtz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!