C ++ - BigInt加法运算二进制

时间:2016-03-03 20:30:16

标签: c++ binary biginteger

我一直在尝试编写一个小的BigInt类作为练习。我想把它作为bools的deque来实现,它代表二进制数字的数字。例如:1234变为=> 0100 0011 0010 0001.正如您所注意到的,我以相反的顺序保留数字的数字,但这些数字顺序正确。

这使得构建课程变得非常快,但操作变得如此棘手,我无法弄清楚如何去做。到目前为止,我有这个:

// Start from proper order + 3, because we store digits in reverse order.
BigInt operator+(int x) {
    BigInt res(*this);
    show_rep(res);
    unsigned bit_place = BIT_FOR_DIGITS - 1;
    auto res_it = res.num.begin() + bit_place;
    bool carry = 0;
    while (x | carry) {
        if (res_it != res.num.end() && res_it + 1 == res.num.end()) {
            for (int i = 0; i < BIT_FOR_DIGITS; ++i)
                res.num.push_back(0);
        }
        bool res_prev = *res_it;
        // combine bits with carry in
        *res_it ^= (x & 1) ^ carry;
        // figure out the carry out
        carry = ((res_prev ^ (x & 1)) & carry) | (res_prev & (x & 1));
        if (!bit_place) {
            // because we do the operations from the rightmost bit to the left
            // Ex: 1001 => 9, we start from right to left.
            res_it += 2 * BIT_FOR_DIGITS - 1;
            bit_place = BIT_FOR_DIGITS - 1;
        }
        else {
            --bit_place;
            --res_it;
        }
        x >>= 1;
    }
    show_rep(res);
    return res;
}

BIT_FOR_DIGITS是4的宏。以上是硬件按位求和运算的简单实现。但是,我面临的问题是以下情况:

  • 假设我想添加127和5.结果应该是132.但是,它输出1212.这是因为,我使用4位来表示数字。因此,当添加发生在7和5之间时,结果12刚刚添加到最后。这个数字没有得到适当的减少。我意识到我需要一个mod运算符,但我不确定如何在二进制文件中执行此操作。那么,我怎样才能通过这种设计正确处理添加?或者我应该完全采用更好的设计?

0 个答案:

没有答案
相关问题