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

How can I add and subtract 128 bit integers in C or C++ if my compiler does not support them?(如果我的编译器不支持,如何在 C 或 C++ 中加减 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 位整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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