How can I add and subtract 128 bit integers in C or C++ if my compiler does not support them?

后端 未结 7 748
我在风中等你
我在风中等你 2020-11-28 11:07

I\'m writing a compressor for a long stream of 128 bit numbers. I would like to store the numbers as differences -- storing only the difference between the numbers rather th

7条回答
  •  星月不相逢
    2020-11-28 11:49

    If all you need is addition and subtraction, and you already have your 128-bit values in binary form, a library might be handy but isn't strictly necessary. This math is trivial to do yourself.

    I don't know what your compiler uses for 64-bit types, so I'll use INT64 and UINT64 for signed and unsigned 64-bit integer quantities.

    class Int128
    {
    public:
        ...
        Int128 operator+(const Int128 & rhs)
        {
            Int128 sum;
            sum.high = high + rhs.high;
            sum.low = low + rhs.low;
            // check for overflow of low 64 bits, add carry to high
            if (sum.low < low)
                ++sum.high;
            return sum;
        }
        Int128 operator-(const Int128 & rhs)
        {
            Int128 difference;
            difference.high = high - rhs.high;
            difference.low = low - rhs.low;
            // check for underflow of low 64 bits, subtract carry to high
            if (difference.low > low)
                --difference.high;
            return difference;
        }
    
    private:
        INT64  high;
        UINT64 low;
    };
    

提交回复
热议问题