Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise XOR of hex numbers in python

How can we XOR hexadecimal numbers in Python? For example, I want to XOR 'ABCD' and '12EF', the answer should be 'B922'.

I used the code below, but it gives the wrong results.

# xor two strings of different lengths def strxor(a, b):     if len(a) > len(b):         return "".join(["%s" % (ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])     else:         return "".join(["%s" % (ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])  key = '12ef' m1 = 'abcd' print(strxor(key, m1)) 
like image 568
Pratibha Avatar asked Jun 20 '12 12:06

Pratibha


People also ask

How do you use XOR hex value in Python?

The 0x at the beginning of the numbers implies that the number is in hex representation. You can use the ^ operator for other integer representations as well.


1 Answers

Whoa. You're really over-complicating it by a very long distance. Try:

>>> print(hex(0x12ef ^ 0xabcd)) 0xb922 

You seem to be ignoring these handy facts, at least:

  • Python has native support for hexadecimal integer literals, with the 0x prefix.
  • "Hexadecimal" is just a presentation detail; the arithmetic is done in binary, and then the result is printed as hex.
  • There is no connection between the format of the inputs (the hexadecimal literals) and the output, there is no such thing as a "hexadecimal number" in a Python variable.
  • The hex() function can be used to convert any number into a hexadecimal string for display.

If you already have the numbers as strings, you can use the int() function to convert to numbers, by providing the expected base (16 for hexadecimal numbers):

>>> print(int("12ef", 16)) 4874 

So you can do two conversions, perform the XOR, and then convert back to hex:

>>> print(hex(int("12ef", 16) ^ int("abcd", 16))) 0xb922 
like image 163
unwind Avatar answered Oct 06 '22 00:10

unwind