Convert hex string to int in Python


Question

How do I convert a hex string to an int in Python?

I may have it as "0xffff" or just "ffff".

1
680
5/14/2016 2:52:52 AM

Accepted Answer

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)
3735928559
>>> print int("10", 0)
10

(You must specify 0 as the base in order to invoke this prefix-guessing behavior; omitting the second parameter means to assume base-10.)

967
4/12/2017 12:21:19 AM

int(hexString, 16) does the trick, and works with and without the 0x prefix:

>>> int("a", 16)
10
>>> int("0xa",16)
10

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon