John Smith
John Smith

Reputation: 123

How to XOR two hex strings in Python 3?

I have two strings stored in 2 separate files, string1="95274DE03C78B0BD" and string2="48656c6c6f20576f".

How can I do bitwise XOR them in Python 3? I expect to get DD42218C5358E7D2 as my result. Please note that I don't want to ord() the strings, my strings are already in hex.

Upvotes: 5

Views: 16257

Answers (1)

Alex Riley
Alex Riley

Reputation: 177048

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).

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:

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

Upvotes: 6

Related Questions