c-有没有一种方法可以用逻辑移位或加法/减法来表示位异或



只是想知道C中的运算符"^"是否可以用有符号整数的移位或减法/加法来表示。

A   B   A^B   A+B
0   0    0    00
0   1    1    01
1   0    1    01
1   1    0    10

因此,Xor可以看作是加法的第一位(无进位)

让我们实现它:

unsigned char a, b;
unsigned char c, answer =0;
int i;
for (i=0; i<8; i++)
{
   c = (a>>i)+(b>>i);  // bit ny bit starting from lsb
   c <<= 7;   // get lost the carry out of addition
   c >>= 7;   // we care only about one-bit result
   c <<= i;   // shift it to its correct position
   answer += c;  // add it to result
}
printf("%Xn", answer);

在此处查找测试示例

最新更新