可能重复:
bitwise XOR of hex numbers in python
我试图在Python中对两个十六进制字符串进行XOR运算,但我真的不知道从哪里开始。
我有两个十六进制字符串:
a = "32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb"
b = "32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f90"
我应该用这个吗?
return "".join([chr((x) ^ (y)) for (x,y) in zip(a[:len(b)], b)])
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
我不明白上面两个代码的区别。为什么选择chr
和ord
?我也看到人们在使用int(hex,16)
。
发布于 2013-01-25 16:50:16
你在这里遗漏了一些东西。
首先,您不希望对这些字符串进行XOR运算。您拥有编码形式的字符串,因此,您需要首先对它们执行.decode()
操作:
binary_a = a.decode("hex")
binary_b = b.decode("hex")
然后,正如前面提到的,一旦两个序列中的一个序列耗尽,zip()
函数就会停止迭代。不需要切片。
您需要循环的第二个版本:首先,您希望获取字符的ASCII值:ord()
生成一个数字。这是必要的,因为^
只适用于数字。
在对数字执行XORing操作之后,您可以使用chr
将数字转换回字符
def xor_strings(xs, ys):
return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys))
xored = xor_strings(binary_a, binary_b).encode("hex")
在最后使用.encode()
,我们将把二进制字符串重新转换成一个格式,打印效果很好。
发布于 2013-01-25 16:44:58
int('', 16)
使用基数16将十六进制字符串转换为整数:
>>> int('f', 16)
15
>>> int('10', 16)
16
所以要这样做:
result = int(a, 16) ^ int(b, 16) # convert to integers and xor them together
return '{:x}'.format(result) # convert back to hexadecimal
https://stackoverflow.com/questions/14526231
复制