Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make bit wise XOR in C

Tags:

c

bit

xor

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;
}
like image 480
sebi Avatar asked Sep 11 '12 18:09

sebi


2 Answers

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;
}     
like image 90
Mike Avatar answered Sep 28 '22 07:09

Mike


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;
}
like image 27
David Schwartz Avatar answered Sep 28 '22 08:09

David Schwartz