Search code examples
pythonstringintegerbinary-operators

"Unsupported operand type(s) for ^: 'str' and 'str'" with Binary in Python 3.x


I'm currently doing a project on binary operators. Right now I have two lists with series of strings with 8 bits of 1s and 0s. Let's say I have this code (a representation of what is produced when I create the two arrays):

arr1 = ['0b01110101', '0b00001111', '0b01001101']
arr2 = ['0b10010100', '0b00000101', '0b00111001']
arr3 = []

I want to run a loop where I perform the XOR binary operator on each value. Here's my loop so far:

for i in len(arr1):
    arr3[i] = arr1[i] ^ arr2[i]

When I run this code I get this error message:

Unsupported operand type(s) for ^: 'str' and 'str'

I've tried doing this:

arr3[i] = bin(arr1[i]) ^ bin(arr2[i])

and it returns this error message:

TypeError: 'str' object cannot be interpreted as an integer

How would I get around this?

EDIT 1: This isn't a duplicate of what it has been flagged as in the comments. I'm not looking how to do a normal XOR binary function. I know how to do that. I'm looking for a way to convert these strings to binary numbers so that I can use the XOR operator on them.


Solution

  • Try this:

    arr1 = ['0b01110101', '0b00001111', '0b01001101']
    arr2 = ['0b10010100', '0b00000101', '0b00111001']
    arr3 = []
    
    for i, _ in enumerate(arr1):
        xor = int(arr1[i], 2) ^ int(arr2[i], 2)
        arr3.append("0b{0:08b}".format(xor))
    

    Output:

    ['0b11100001', '0b00001010', '0b01110100']