如何使用按位添加位?

时间:2014-02-25 21:37:22

标签: c bit-manipulation

我试图找出如何仅使用以下按位操作来添加位(最多2个字节):〜& ^ | << >取代。我一直试着没有运气。我想知道是否有人知道如何。

int logicalByteAdd(int x, int y) {

return ;
}

1 个答案:

答案 0 :(得分:2)

unsigned short add(unsigned short a, unsigned short b)
{
    unsigned short carry = a & b;
    unsigned short result = a ^ b;
    while(carry != 0)
    {
        unsigned short shiftedcarry = carry << 1;
        carry = result & shiftedcarry;
        result ^= shiftedcarry;
    }
    return result;
}
Proof of Correctness

提供的

Mooing Duck