如何添加和减去128位整数

如何添加和减去128位整数

本文介绍了如果我的编译器不支持C或C ++,如何添加和减去128位整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为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;
};

这篇关于如果我的编译器不支持C或C ++,如何添加和减去128位整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:26