简体   繁体   中英

How to XOR to equal hex strings?

Could someone help to understand how it works in python (2.7.3 version)?

for,example there are two hex strings

a='5f70a65ac'
b='58e7e5c36'

how can I xor it properly?

I tried use something like that hex (0x5f0x70 ^ 0x580xe70) , but it doesn't work

Convert the strings to integers before trying to do math on them, then back to string afterward.

print "%x" % (int(a, 16) ^ int(b, 16))

I'm using % here to convert back to string rather than hex() because hex() adds 0x to the beginning (and L to the end if the value is a long integer). You can strip those off, but easier just to not generate them in the first place.

You could also just write them as hex literals in the first place:

a=0x5f70a65ac
b=0x58e7e5c36
print "%x" % (a ^ b)

However, if you're reading them from a file or getting them from a user or whatever, the first approach is what you need.

a = '5f70a65ac'
b = '58e7e5c36'
h = lambda s: ('0' + s)[(len(s) + 1) % 2:]
ah = h(a).decode('hex')
bh = h(b).decode('hex')
result = "".join(chr(ord(i) ^ ord(j)) for i, j in zip(ah, bh)).encode("hex")

Currently, this only works with equally-lengthed strings, but can easily extended to work with arbitrary-lengthed ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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