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 = []
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
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 = []
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