XOR'ing each bit of a binary string in Python

Question:

I have two binary strings (not integer) for example 0101 and 0010, I need to XOR these two binary strings and then XOR the each bit of the result again. XOR of these two results in 0111, now I want to achieve the result 0 xor 1 xor 1 xor 1. How can I achieve it in python?

I have XORed the two strings in result variable, now I need to find the XOR of each bit in result

a = "0101"
b = "0010"
result = []
for x, y in zip(a, b):
    if x == y:
        result.append('0')
    else:
        result.append('1')
final = []
Asked By: efe373

||

Answers:

Working with strings

You can use the same logic you used on two inputs, to reduce a single input:

from functools import reduce

final = reduce(lambda x, y: '0' if x == y else '1', result)

Working with ints

Alternatively, you can just transform the inputs to ints by using int(x, 2). So you can have:

result = int(a, 2) ^ int(b, 2)

And now you just need to bit-wise XOR result. That is mentioned here and is basically a parity check which can be easily done (Python >= 3.10) with

final = result.bit_count() & 1
Answered By: Tomerikoo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.