How to make bit wise XOR in C

夙愿已清 提交于 2019-11-27 10:24:00

问题


I'm trying to get into C programming, and I'm having trouble writing a bitwise XOR function with only ~ and & operators. Example: bitXor(4, 5) = 1. How can I achieve this?

So far I have this:

int bitXor(int x, int y) {

    return z;
}

回答1:


Well, let's think about this. What does XOR do?

x   y    XOR
------------
0   0     0
1   0     1
0   1     1
1   1     0

So how do we turn that into a function? Let's think about AND, and the inverse order of AND (~x&~y) (this happens to be NOR):

              (~x&~y)
 x   y   AND    NOR   
 ---------------------
 0 & 0  = 0      1    
 1 & 0  = 0      0 
 0 & 1  = 0      0
 1 & 1  = 1      0

Looking at those two outputs, it's pretty close, all we have to do is just NOR the two previous outputs (x AND y) (x NOR y) and we'd have the solution!

  (a)       (b)    ( a NOR b )
x AND y   x NOR y    ~a & ~b
-------------------------------
   0         1          0
   0         0          1
   0         0          1
   1         0          0

Now just write that out:

a = ( x & y )
b = ( ~x & ~y )
XOR'd result = (~a & ~b)

BINGO! Now just write that into a function

int bitXor(int x, int y) 
{
    int a = x & y;
    int b = ~x & ~y;
    int z = ~a & ~b;
    return z;
}     



回答2:


Using NAND logic:

int bitNand(int x, int y)
{
    return ~ (x & y);
}

int bitXor(int x, int y)
{
    return bitNand( bitNand(x, bitNand(x, y)),
                    bitNand(y, bitNand(x, y)) );
}

Or:

int bitXor(int x, int y)
{
    return ~( (x & y) | (~x & ~y) );
}

Or:

int bitXor(int x, int y)
{
    return (x & ~y) | (~x & y);
}

Of course this is easier:

int bitXor(int x, int y)
{
    return x ^ y;
}



回答3:


It is easily seen that

x ^ y = (x | y) & ~(x & y)

so it remains to express | by only & and ~. De Morgan's laws tell us

x | y = ~(~x & ~y)



回答4:


I want it to write it only with ~ and &

That counts for NAND gates, right? After studying this circuit diagram:

int z = ~ ((~(a & ~(a & b)) & (~(b & ~(a & b)));

The same applies for the non-bitwise, i. e. logic one as well, just substitute ! instead of the ~.




回答5:


You can perform a bitwise XOR operation in c using the ^ operator.




回答6:


int bitXor(int x, int y) {
  return ~(~(~x & y) & ~(x & ~y));
}

explanation:

x ^ y = (~x & y) | (x & ~y) = ~(~(~x & y) & ~(x & ~y))

The last procedure is making use of De Morgan's laws




回答7:


int xorro(a, b)
{
    if (a == b)
        return 0;
    return 1; 
}


来源:https://stackoverflow.com/questions/12375808/how-to-make-bit-wise-xor-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!