Hic*_*ick 45 python string bitwise-operators
我想在python中执行按位异或两个字符串,但python中不允许使用xor字符串.我该怎么做 ?
Mar*_*ers 60
您可以将字符转换为整数,然后将xor转换为:
l = [ord(a) ^ ord(b) for a,b in zip(s1,s2)]
Run Code Online (Sandbox Code Playgroud)
这是一个更新的函数,以防你需要一个字符串作为XOR的结果:
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))
Run Code Online (Sandbox Code Playgroud)
看到它在线工作:ideone
Dun*_*can 26
如果你想对字节或单词进行操作,那么你最好使用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'
Run Code Online (Sandbox Code Playgroud)
小智 15
对于bytearrays,您可以直接使用XOR:
>>> 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')
Run Code Online (Sandbox Code Playgroud)
Pau*_*McG 12
这是你的字符串XOR'er,大概是为了一些温和的加密形式:
>>> 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!
Run Code Online (Sandbox Code Playgroud)
请注意,这是一种非常弱的加密形式.观察给定空字符串进行编码时会发生什么:
>>> codebreak = xorWord(" ", code)
>>> print codebreak
SECRET
Run Code Online (Sandbox Code Playgroud)
yot*_*ota 11
python3的一个衬里是:
def bytes_xor(a, b) :
return bytes(x ^ y for x, y in zip(a, b))
Run Code Online (Sandbox Code Playgroud)
where a
,b
而返回的值当然bytes()
不是str()
不能轻松,我喜欢python3 :)