且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

添加仅使用位运算符两个整数?

更新时间:2022-12-09 19:36:02

下面是您娱乐的例子

unsigned int myAdd(unsigned int a, unsigned int b)
{
    unsigned int carry = a & b;
    unsigned int result = a ^ b;
    while(carry != 0)
    {
        unsigned int shiftedcarry = carry << 1;
        carry = result & shiftedcarry;
        result ^= shiftedcarry;
    }
    return result;
}

循环可以展开。它的执行次数,取决于操作数设置的位数,但它从来没有超过 unsigned int类型的宽度。一旦执行变为 0 ,接下来的迭代不会改变任何东西。

The loop could be unrolled. Number of times it executes, depends on the number of bits set in operands, but it's never greater than the width of unsigned int. Once carry becomes 0, next iterations don't change anything.