如果我的编译器不支持,如何在 C 或 C++ 中加减 128 位整数?

2022-01-14 00:00:00 integer c++ 128-bit

我正在为一长串 128 位数字编写压缩器.我想将数字存储为差异 - 仅存储数字之间的差异而不是数字本身,因为我可以将差异打包在更少的字节中,因为它们更小.

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.

但是,对于压缩,我需要减去这些 128 位值,而对于解压缩,我需要添加这些值.我的编译器的最大整数大小为 64 位宽.

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?

推荐答案

如果您只需要加法和减法,并且您已经有二进制形式的 128 位值,那么库可能很方便,但不是绝对必要的.自己做这个数学很简单.

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.

我不知道你的编译器对 64 位类型使用什么,所以我将使用 INT64 和 UINT64 来处理有符号和无符号 64 位整数.

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

相关文章