Search code examples
c++integer128-bit

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


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 than the numbers themselves because I can pack the differences in fewer bytes because they are smaller.

However, for compression then I need to subtract these 128 bit values, and for decompression I need to add these values. Maximum integer size for my compiler is 64 bits wide.

Anyone have any ideas for doing this efficiently?


Solution

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