How can I XOR two numbers without using the ^ operator?

Question

How can I XOR two numbers without using the ^ operator?

Answer

It might help to write out the numbers on paper and do it as you would any other math. For bit strings of different lengths, simply write out the numbers and fill in the leftmost missing bits with 0s. For example:
0b10011001 ^ 0b1111
We’d write that out as follows:

  1001 1001
^ 0000 1111
-------------
  1001 0110
1 Like

I agree that it is easy to do this on paper or in my head.
But I understood the task to mean “write Python code that does the same job without using ^”.

I was hoping to find a solution for that here.
My main problem is to make the numbers the same length before comparing them with a loop.
Thanks!

4 Likes

One approach will be to convert the numbers to strings, and pad out the left side of the shorter string with zeroes.

Say we have two numbers, 218 and 47 and we wish to express,

218 XOR 47

The first step will be to recast both numbers as strings. Hint: bin() returns str objects, '0b...' Of course there is a manual way to convert decimal to binary, but for now we’ll use the provided function to get to the strings themselves.

>>> a = bin(218)
>>> b = bin(47)
>>> a, b
('0b11011010', '0b101111')
>>> len(a), len(b)
(10, 8)
>>> 

We will first need to remove the 0b before padding out the shorter of the two.

>>> c, d = a[2:], b[2:]
>>> while len(d) < len(c):
    d = '0' + d

    
>>> c, d
('11011010', '00101111')
>>> 

Now both strings are the same length so we can begin comparing the characters at the same position in each.

>>> xor = '0b'
>>> for i in range(len(c)):
    if c[i] != d[i]:
        xor += '1'
    else:
        xor += '0'

        
>>> xor
'0b11110101'
>>> bin(218 ^ 47)
'0b11110101'
>>> 
13 Likes

Thanks a lot, Roy!

I did not think of concatenating zeroes to the left.

Other than that, I made the function more general (decides which arg is shorter, swaps if necessary to let c be the shorter, then padds c).
And (without looking at your code I did not check the bits for equality but checked 1) if the concat to ‘01’ or ‘10’
2) checked if their int add up to 1
So, with your help for the padding, I found my own solution.
Thanks!!

1 Like

You can use a combination of other logic operators to run as the ^ (XOR) operator.

The following code returns the same result than print bin(0b1110 ^ 0b101):

print bin((0b1110 | 0b101) & ~(0b1110 & 0b101))