How to convert an hex number to binary in Python?

Problem

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:

bin (my_hex)
TypeError: 'str' object cannot be interpreted as an integer

Converting the hexadecimal to integer, and then converting to binary also renders an error:

bin (int(my_hex))
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:

'0b1000000000'

We can cast the binary to int to verify our conversion.

int('0b1000000000', base=2)

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:

0x502299d8

Next we’ll convert our hex string:

binascii.unhexlify(my_hex[2:])

This will return the following bytes object:

b'P"\x99\xd8'

We can convert back this to integer:

int.from_bytes(b'P"\x99\xd8', "big")

This will render our original integer number.

1344444888

Additional Learning

How to make a multiplication of two numeric columns of a pandas DataFrame?