我想在Python中对两个字符串执行位异或操作,但是Python不允许对字符串进行异或运算。我该怎么做?
我想在Python中对两个字符串执行位异或操作,但是Python不允许对字符串进行异或运算。我该怎么做?
您可以将字符转换为整数,然后将它们异或:
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
bytes(x ^ y for x, y in zip(s1, s2))
的代码进行两个字符串的按位异或操作。你可以在下面的链接中查看相关信息:https://dev59.com/Z3E85IYBdhLWcg3wyGp_#28481974 - yota如果你想操作字节或单词,那么最好使用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'
>>> 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')
Python3的一行代码是:
def bytes_xor(a, b) :
return bytes(x ^ y for x, y in zip(a, b))
当然,a
, b
和返回的值都应该是bytes()
而不是str()
。
再简单不过了,我喜欢Python3 :)
这是一个字符串异或器,可能用于某种轻度的加密:
>>> src = "Hello, World!"
>>> code = "secret"
>>> xorWord = lambda ss,cc: ''.join(chr(ord(s)^ord(c)) for s,c in zip(ss,cc*100))
>>> encrypt = xorWord(src, code)
>>> encrypt
';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
>>> decrypt = xorWord(encrypt,code)
>>> print decrypt
Hello, World!
>>> codebreak = xorWord(" ", code)
>>> print codebreak
SECRET
def strxor (s0, s1):
l = [ chr ( ord (a) ^ ord (b) ) for a,b in zip (s0, s1) ]
return ''.join (l)
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])
s1 = '00000001'
s2 = '11111110'
int(s1,2) ^ int(s2,2)
以下演示了用 m 对字符串 s 进行异或,然后再次执行此过程以进行反向操作:
>>> s='hello, world'
>>> m='markmarkmark'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'\x05\x04\x1e\x07\x02MR\x1c\x02\x13\x1e\x0f'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'hello, world'
>>>
def xor_strings(s1, s2):
max_len = max(len(s1), len(s2))
s1 += chr(0) * (max_len - len(s1))
s2 += chr(0) * (max_len - len(s2))
return ''.join([chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(s1, s2)])