c++ - 除法不跨越字节

标签 c++ math biginteger integer-division

我正在尝试对由 2 个 uint64_t 组成的 uint128_t 进行除法。奇怪的是,该函数适用于 uint64_t,仅设置了较低的值且较高的值 = 0。我不明白为什么。

下面是除法和位移的代码

class uint128_t{
   private:
      uint64_t UPPER, LOWER;
   public:
      // lots of stuff

    uint128_t operator<<(int shift){
        uint128_t out;
        if (shift >= 128)
            out = uint128_t(0, 0);
        else if ((128 > shift) && (shift >= 64))
            out = uint128_t(LOWER << (64 - shift), 0);
        else if (shift < 64)
            out = uint128_t((UPPER << shift) + (LOWER >> (64 - shift)), LOWER << shift);
        return out;
    }

    uint128_t operator<<=(int shift){
        *this = *this << shift;
        return *this;
    }

    uint128_t operator/(uint128_t rhs){
            // copy of numerator = copyn
            uint128_t copyn(*this), quotient = 0;// constructor: uint128_t(T), uint128_t(S, T), uint128_t(uint128_t), etc
            while (copyn >= rhs){
                // copy of denomiator = copyd
                // temp is the current quotient bit being worked with
                uint128_t copyd(rhs), temp(1);
                // shift the divosr to the highest bit
                while (copyn > (copyd << 1)){
                    copyd <<= 1;
                    temp <<= 1;
                }
                copyn -= copyd;
                quotient += temp;
            }
            return quotient;
        }
// more stuff
};

请忽略我对内存管理的公然漠视。

最佳答案

out = uint128_t(LOWER << (64 - shift), 0);错了——应该是 shift - 64相反。

作为样式说明,ALL_CAPITALS 通常只保留给常量。变量和成员应该主要使用小写字母。

关于c++ - 除法不跨越字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6147140/

相关文章:

带有 BigInteger 指数的 Java BigInteger pow

c++ - MSBuild 错误 MSB4095 : The item metadata %(RootDir) is being referenced without an item name

c++ - boost::archive::text_iarchive 构造函数异常

C++ vector 排序

java - 调整图像的对比度

c - C 中 x64 上的 128 位算术

c++ - 什么是智能指针管理的资源,而它们的内存不是new分配的?

java - 嵌套循环与硬编码矩阵乘法的性能

python - 将奇数舍入为偶数的最佳方法是什么?

Javascript/Nodejs 检查某些内容是否为 bigint 类型?