Reputation: 659
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
Upvotes: 2
Views: 1526
Reputation: 184395
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.
Upvotes: 7
Reputation: 91139
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.
Upvotes: 1