We would like to convert an hexadecimal number to a binary number system (or from base 16 to base 2).
Let’s assume that we have the following hexadecimal (which represent the integer value 512)
my_hex = '0x200'
Running a simple conversion using the bin() function renders a TypeError exception:
TypeError: 'str' object cannot be interpreted as an integer
Converting the hexadecimal to integer, and then converting to binary also renders an error:
ValueError: invalid literal for int() with base 10: '0x200'
Change hexadecimal to binary
The solution is to simply tweak the conversion to integer a bit. We need to make sure to specify that my_hex is a hexadecimal, that is a number of base=16. Then, conversion to binary will work:
bin (int(my_hex, base=16))
This will return the following binary:
We can cast the binary to int to verify our conversion.
This will return the integer 512.
Convert hex to bytes using binascii
We can convert hexadecimals to bytes using the binascii library. First off make sure to import the library (otherwise you will receive a ModuleNotFound exception).
Then use the unhexlfy() method to revert your hex string to bytes.
my_hex = hex(1344444888) print(my_hex)
This will return the following string:
Next we’ll convert our hex string:
This will return the following bytes object:
We can convert back this to integer:
This will render our original integer number.