【问题标题】:Is there a way to represent bitwise xor with logical shifts or addition/subtraction?有没有办法用逻辑移位或加/减来表示按位异或?
【发布时间】:2014-09-23 02:19:56
【问题描述】:

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

【问题讨论】:

  • 您是否考虑过使用 AND、OR 和 NOT 的组合? en.wikipedia.org/wiki/XOR_gate#Alternatives
  • 您是否需要以易于理解的可读格式来表示它(极不可能),或者您想要其他方式来综合行为(可能通过几个步骤的功能)?
  • @AlokSave 后者。我想知道是否可以通过非常基本的操作来模仿这种行为。
  • @Steady: This 应该有帮助

标签: c syntax operators


【解决方案1】:
A   B   A^B   A+B
0   0    0    00
0   1    1    01
1   0    1    01
1   1    0    10

所以异或,只能看成加法的第一位(没有进位)

让我们实现它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多