Search code examples
pythonxor

How to XOR two binary strings in python


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


Solution

  • 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.