-2

I need to do XOR operation between two binary strings.

xor("00110011", "11001100") = "11111111"

i am currently using this function

def xor(x, y):
    ans = ""
    for i in xrange(len(x)):
        if x[i] == "0" and y[i] == "1" or x[i] == "1" and y[i] == "0":
            ans += "1"
        else:
            ans += "0"
    return ans

please give me good method

Atul
  • 546
  • 4
  • 16
  • You can use parenthesis, if you like. BTW, is there a specific problem in this code? – thefourtheye Jul 05 '16 at 13:22
  • Please [edit] your question and include a sample of your input and the expected output. –  Jul 05 '16 at 13:24
  • 2
    you can use `^` - the xor operator. Please see http://stackoverflow.com/questions/19414093/how-to-xor-binary-with-python – gunzapper Jul 05 '16 at 13:25
  • If you are using Python 3, these are not binary strings in the Python sense. –  Jul 05 '16 at 13:32
  • You need to tell us about edge-cases too. What happens with with `xor('01', '00')` for example? Is the output `'1'` or `'01'`. In other words, should the output be *the same string length, always*? – Martijn Pieters Jul 05 '16 at 13:35

3 Answers3

6

If you must use strings of '0' and '1' characters, just use a mapping:

_xormap = {('0', '1'): '1', ('1', '0'): '1', ('1', '1'): '0', ('0', '0'): '0'}
def xor(x, y):
    return ''.join([_xormap[a, b] for a, b in zip(x, y)])

otherwise, just convert to two integers, XOR those and re-format back to a binary string:

def xor(x, y):
    return '{1:0{0}b}'.format(len(x), int(x, 2) ^ int(y, 2))

This ensures that the resulting string has the same length by zero-padding to the length of x.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4
def xor(x, y):
    return '{0:b}'.format(int(x, 2) ^ int(y, 2))

Credits to this answer. Contrary to popular belief, Python does have bitwise operators.

Community
  • 1
  • 1
Nee
  • 566
  • 2
  • 17
  • 3
    Note that this can lead to a *shorter* binary string, the null-padding is lost. Try it with `xor('00000001', '00000000')` for example. – Martijn Pieters Jul 05 '16 at 13:27
-2

If you need to reinvent the whell

def alternative_xor(x, y):
  a = int(x)
  b = int(y)  
  return (a & ~b) | (~a & b)
gunzapper
  • 457
  • 7
  • 19