小编典典

仅使用按位运算符将两个整数相加?

c#

在C#中,是否可以执行两个32位整数的和而不使用if..else,循环等?

也就是说,是否可以仅使用按位运算OR(|),AND(&),XOR(^),NOT(!),左移(<<)和右移(>>)来完成?


阅读 435

收藏
2020-05-19

共1个答案

小编典典

这是您娱乐的例子

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。一旦carry成为0,接下来的迭代就不会改变任何东西。

2020-05-19