如何对 python 中的两个二进制字符串进行异或
How to XOR two binary strings in python
我需要在两个二进制字符串之间进行异或运算。
xor("00110011", "11001100") = "11111111"
我目前正在使用这个功能
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
请给我好方法
def xor(x, y):
return '{0:b}'.format(int(x, 2) ^ int(y, 2))
感谢 this answer. Contrary to popular belief, Python does have bitwise operators。
如果您必须使用'0'
和'1'
字符的字符串,只需使用映射:
_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)])
否则,只需转换为两个整数,对它们进行异或,然后重新格式化回二进制字符串:
def xor(x, y):
return '{1:0{0}b}'.format(len(x), int(x, 2) ^ int(y, 2))
这通过零填充到 x
的长度来确保生成的字符串具有相同的长度。
如果需要重新发明轮子
def alternative_xor(x, y):
a = int(x)
b = int(y)
return (a & ~b) | (~a & b)
我需要在两个二进制字符串之间进行异或运算。
xor("00110011", "11001100") = "11111111"
我目前正在使用这个功能
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
请给我好方法
def xor(x, y):
return '{0:b}'.format(int(x, 2) ^ int(y, 2))
感谢 this answer. Contrary to popular belief, Python does have bitwise operators。
如果您必须使用'0'
和'1'
字符的字符串,只需使用映射:
_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)])
否则,只需转换为两个整数,对它们进行异或,然后重新格式化回二进制字符串:
def xor(x, y):
return '{1:0{0}b}'.format(len(x), int(x, 2) ^ int(y, 2))
这通过零填充到 x
的长度来确保生成的字符串具有相同的长度。
如果需要重新发明轮子
def alternative_xor(x, y):
a = int(x)
b = int(y)
return (a & ~b) | (~a & b)