只是想知道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("%X\n", answer);
查找测试示例here