只是想知道C中的运算符“^”是否可以用有符号整数的移位或减法/加法来表示。
答案 0 :(得分:0)
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("%X\n", answer);
找到测试示例here