Python:异或十六进制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14526231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: XOR hex strings
提问by Kok Leong Fong
Possible Duplicate:
bitwise XOR of hex numbers in python
可能的重复:
python 中十六进制数的按位异或
I am trying to XOR two hex strings in Python and did not really know where to start from.
我试图在 Python 中对两个十六进制字符串进行异或运算,但真的不知道从哪里开始。
I have two hex strings:
我有两个十六进制字符串:
a = "32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb"
b = "32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f90"
Should I be using this ?
我应该使用这个吗?
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)])
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)])
I don't understand the difference with the two codes above. Why chrand ord? I have also seen people using int(hex,16).
我不明白上面两个代码的区别。为什么chr和ord?我也看到有人使用int(hex,16).
采纳答案by phant0m
You are missing a couple of things here.
你在这里错过了一些东西。
First, you will not want to XOR thosestrings. You have the strings in an encoded form, therefore, you need to .decode()them first:
首先,您不会想要对这些字符串进行异或。您有编码形式的字符串,因此,您.decode()首先需要它们:
binary_a = a.decode("hex")
binary_b = b.decode("hex")
Then, as already mentioned, the zip()function stops iterating as soon as one of the two sequences is exhausted. No slicing is needed.
然后,正如已经提到的,zip()一旦两个序列之一用完,该函数就会停止迭代。不需要切片。
You need the second version of the loop: First, you want to get the ASCII value of the characters: ord()produces a number. This is necessary because ^only works on numbers.
您需要循环的第二个版本:首先,您要获取字符的 ASCII 值:ord()生成一个数字。这是必要的,因为^仅适用于数字。
After XORing the numbers, you then convert the number back into a character with chr:
对数字进行异或后,然后将数字转换回字符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")
Using .encode()at the end, we get the binary string back into a form, that prints nicely.
最后使用.encode(),我们将二进制字符串恢复为一种打印效果很好的形式。
回答by glyphobet
int('', 16)converts a hex string to an integer using base 16:
int('', 16)使用基数 16 将十六进制字符串转换为整数:
>>> int('f', 16)
15
>>> int('10', 16)
16
So do this:
所以这样做:
result = int(a, 16) ^ int(b, 16) # convert to integers and xor them together
return '{:x}'.format(result) # convert back to hexadecimal

