如何在Python中对两个字符串进行按位异或?
我想在Python中对两个字符串进行按位异或操作,但Python不允许对字符串进行异或运算。我该怎么做呢?
12 个回答
17
对于字节数组,你可以直接使用异或运算:
>>> b1 = bytearray("test123")
>>> b2 = bytearray("321test")
>>> b = bytearray(len(b1))
>>> for i in range(len(b1)):
... b[i] = b1[i] ^ b2[i]
>>> b
bytearray(b'GWB\x00TAG')
28
如果你想处理字节或者字(word),那么用Python的数组类型会比字符串更合适。如果你在处理固定长度的数据块,可能可以使用H或L格式来处理字而不是字节,但在这个例子中我只是用了'B':
>>> import array
>>> a1 = array.array('B', 'Hello, World!')
>>> a1
array('B', [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33])
>>> a2 = array.array('B', ('secret'*3))
>>> for i in range(len(a1)):
a1[i] ^= a2[i]
>>> a1.tostring()
';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
70
你可以把字符转换成整数,然后对这些整数进行异或运算:
l = [ord(a) ^ ord(b) for a,b in zip(s1,s2)]
这里有一个更新后的函数,如果你需要异或运算的结果是一个字符串,可以用这个:
def sxor(s1,s2):
# convert strings to a list of character pair tuples
# go through each tuple, converting them to ASCII code (ord)
# perform exclusive or on the ASCII code
# then convert the result back to ASCII (chr)
# merge the resulting array of characters as a string
return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))
你可以在线查看它的运行效果: ideone