Convert hex string to int in Python


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

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

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

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

The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)


a = int('0x100', 16)
print(a)   #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100

Convert hex string to int in Python

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

To convert a string to an int, pass the string to int along with the base you are converting from.

Both strings will suffice for conversion in this way:

>>> string_1 = "0xffff"
>>> string_2 = "ffff"
>>> int(string_1, 16)
>>> int(string_2, 16)

Letting int infer

If you pass 0 as the base, int will infer the base from the prefix in the string.

>>> int(string_1, 0)

Without the hexadecimal prefix, 0x, int does not have enough information with which to guess:

>>> int(string_2, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: 'ffff'


If you're typing into source code or an interpreter, Python will make the conversion for you:

>>> integer = 0xffff
>>> integer

This won't work with ffff because Python will think you're trying to write a legitimate Python name instead:

>>> integer = ffff
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ffff' is not defined

Python numbers start with a numeric character, while Python names cannot start with a numeric character.

To convert a DWORD from hex to a signed integer , implement two's complement like this:

~ (0xffffffff - int('0xdeadbeef', 16)) + 1