Monday, December 30, 2013

Swap using XOR gate

XOR or Exclusive-OR is a digital logic gate. Digital Logic permits only two value or states (the binary states) of 0 and 1 as inputs or outputs. A gate usually has two or more inputs and a single output

Simply stating an XOR gate give 0 output when the inputs are same(both . When the inputs are different it gives 1 as ouput.

1 XOR 1 = 0
0 XOR 0 = 0
1 XOR 0 = 1
0 XOR 1 = 0

We can compile the result into a cleaner tabular form known as truth table.
Going with existing terminology of digital logic, we can say that 1 represent True and 0 represent False.


a   b     a XOR b
0   0           0
0   1           1
1   0           1
1   1           0

What would be 1010111 XOR 1000101
1010111
1000101
-----------
0010010 (Answer)

8 XOR 1=9?Covert both to binary equivalent and add extra zeros to left hand side if necessary
8=1000
1=0001 [zeros added to left]
---------
9=1001


XOR be used to Swap binary data in following manner
a= a XOR b
b= a XOR b
a= a XOR b

lol?

Say a= 7 and b=2
binary equivalent of 7 is 111 and of 2 is 010
a= 111 XOR 010 = 101 
b= 101 XOR 010 = 111
a= 101 XOR 111 = 010
a=2, b=7

In C Language bitwise XOR Operator is represented by ^ (exponent) sign.
so swap will be be done by
a=a^b;
b=a^b;
a=a^b;







 

No comments:

Post a Comment