问题
I was trying to figure out how to add bits (up to 2 bytes) using only the following bitwise operations: ~ & ^ | << >>. I've been trying for a while with no luck. I was wondering if anyone knew how.
int logicalByteAdd(int x, int y) {
return ;
}
回答1:
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 provided by Mooing Duck
来源:https://stackoverflow.com/questions/22026777/how-to-add-bits-using-bitwise