Python Hex String to Decimal

4.3/5 - (3 votes)

Question

πŸ’¬ How to convert a hexadecimal string to a decimal integer value in Python?

Answer Summary

To convert a hex string to a decimal integer value, pass the hex string into the

  • int() function with base argument such as int('0xfff', base=16), or
  • eval() function such as eval('0xfff').

The result is a decimal integer value with base 10.

Code Examples int()

>>> int('0x1', base=16)
1
>>> int('0xa', base=16)
10
>>> int('0xff', base=16)
255
>>> int('0xdeadbeef', base=16)
3735928559

Code Examples eval()

>>> eval('0x1')
1
>>> eval('0xa')
10
>>> eval('0xff')
255
>>> eval('0xdeadbeef')
3735928559

Discussion

Personally, I like the eval() function approach more because it is shorter and more concise.

I’m a complete nut in making Python programs shorter—so much so that I have written a whole book on it called Python One-Liners.

Objectively, however, I’d recommend using the int() function with the explicit base=16 argument because it’s just more pythonic in that there will be less confusion and fewer security concerns:

Although in most cases, using eval() is not a concern whatsoever, it may be dangerous in some cases because it opens up an attack vector where a hacker could somehow change the string passed into the eval() function and execute arbitrary Python code on your computer.

Although the probability of this “cross-site scripting” attack occurring is very low, the risk is just not worth it.

Further Reading

I have written in-depth tutorials on this or related topics on the Finxter blog. Find them here: