如何使用按位添加位? [英] How to add bits using bitwise?
本文介绍了如何使用按位添加位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图弄清楚如何仅使用以下按位运算来添加位(最多2个字节):〜& ^ | << >>.我已经尝试了一段时间没有运气了.我想知道是否有人知道.
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 ;
}
推荐答案
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;
}