# Find XOR of two numbers without using XOR operator

Write a program to find XOR of two numbers without using XOR operator.

Naive Solution would be to consider every bit present in both numbers one by one (either from left or right) and compare them. If the current bit is same in both numbers (i.e. both are 0 or both are 1), we set it as 0 else we set it as 1 and move to next pair of bits until all bits are processed.

The expression ((x | y) – (x & y)) is equivalent to x ^ y (finding XOR of two numbers x and y). XOR works by setting the bits which are set in either of one of the given numbers (0 ^ 1 = 1,
1 ^ 0 = 1)
and finally taking out the common bits present in both numbers (1 ^ 1 = 0).
For example,

01000001   |                 (x = 65)
01010000                     (y = 80)
~~~~~~~~
01010001                     (x | y)

01000001   &                 (x = 65)
01010000                     (y = 80)
~~~~~~~~
01000000                     (x & y)

Now the result x ^ y would be (x | y) – (x & y) = (01010001 – 01000000) = 00010001

## C++

Output:

First number in binary is 01000001
Second number in binary is 01010000

XOR is 00010001

Read More –

Suggested Read: https://graphics.stanford.edu/~seander/bithacks.html

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

### Leave a Reply

Subscribe
Notify of
Guest
TheDarkKnight

Hey,
I am unable to understand how x^y = ((x | y) – (x & y)).
I did a quick search on wikipedia and it says x^y = x.y’ + x’.y = (x+y).(x’+y’) where x’ represents complement of x.
Can you please explain?