Convert hex string to integer in Python

Without the 0x prefix, you need to specify the base explicitly, otherwise there’s no way to tell:

x = int("deadbeef", 16)

With the 0x prefix, Python can distinguish hex and decimal automatically:

>>> print(int("0xdeadbeef", 0))
>>> print(int("10", 0))

(You must specify 0 as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter, int() will assume base-10.)

Leave a Comment