# 我该如何在C中使用mod 2加法来进行XOR？

##### 问题描述投票：1回答：2

``````unsigned char XOR_BIT(unsigned char A, unsigned char B)
{
unsigned char x;
unsigned char y;
unsigned char c;
unsigned char o;
unsigned char output = 0;
for(c = 0; c < 8; c++)
{
printf("=========Round %u=============\n", c);
x = (A & (1 << c));
printf("x: %u\n", x);
y = (B & (1 << c));
printf("y: %u\n", y);
o = (x + y) % 2;
printf("o: %u\n", o);
output |= (o << c);
printf("output: %u\n", output);
}
return output;
}
``````

``````=========Round 0=============
x: 1
y: 0
o: 1
output: 1
=========Round 1=============
x: 0
y: 2
o: 0
output: 1
=========Round 2=============
x: 4
y: 0
o: 0
output: 1
=========Round 3=============
x: 0
y: 8
o: 0
output: 1
=========Round 4=============
x: 0
y: 0
o: 0
output: 1
=========Round 5=============
x: 0
y: 0
o: 0
output: 1
=========Round 6=============
x: 0
y: 0
o: 0
output: 1
=========Round 7=============
x: 0
y: 0
o: 0
output: 1
MyXOR: 1
Standard XOR: 15
``````

[我怀疑我是误解了所需的按位操作，或者我有一个代码错误，但是我在此领域没有足够的知识来确定问题。

1. 一次抓取每个字节1位
2. 在每对位上执行mod 2加法
3. 将每个结果位存储在输出中
4. 将输出位返回为1字节
c bit-manipulation bitwise-operators bitwise-xor
##### 2个回答
2

``````x = (A >> c) & 1;
y = (B >> c) & 1;
``````

1

（（5 + 10）mod 2是1，而不是5，但这与按位异或结果也不相同。您已或多或少正确地推断出断言适用于各个位，但是您的代码表明您可能尚未完全理解这一点。

``````    x = !(A & (1 << c));
y = !(B & (1 << c));
o = (x + y) % 2;
output |= (o << c);
``````