简体   繁体   English

如何在Python 3中对两个十六进制字符串进行异或?

[英]How to XOR two hex strings in Python 3?

I have two strings stored in 2 separate files, string1="95274DE03C78B0BD" and string2="48656c6c6f20576f" . 我有两个字符串存储在2个单独的文件中, string1="95274DE03C78B0BD"string2="48656c6c6f20576f"

How can I do bitwise XOR them in Python 3? 我怎么能在Python 3中对它们进行按位异或? I expect to get DD42218C5358E7D2 as my result. 我希望得到DD42218C5358E7D2作为我的结果。 Please note that I don't want to ord() the strings, my strings are already in hex. 请注意,我不想ord()字符串,我的字符串已经是十六进制。

Strings in Python 3 are unicode objects and so a string of hexadecimal characters does not correspond to the binary representation of the integer in memory (which you need to use XOR). Python 3中的字符串是unicode对象,因此一串十六进制字符不对应于内存中整数的二进制表示(您需要使用XOR)。

With this in mind, you could interpret the strings as base-16 integers first, XOR them, and convert the resulting integer back to a hex string: 考虑到这一点,您可以首先将字符串解释为base-16整数,将它们异或,并将结果整数转换回十六进制字符串:

>>> hex(int(string1, 16) ^ int(string2, 16))
'0xdd42218c5358e7d2'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM