您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

这是您娱乐的例子

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

其他 2022/1/1 18:15:10 有446人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶