How to Convert a Hexadecimal String to an Integer in Python?

In Python, you can use the int() method (with a base 16 as the second argument) to convert (uppercase or lowercase) hexadecimal string to its integer equivalent, for example, like so:

num = int('ddd5', 16)

print(num) #=> 56789
num = int('DDD5', 16)

print(num) #=> 56789

This also works with hexadecimal strings that have the "0x" (or "0X") hexadecimal radix prefix:

# Python 2.6+
num = int('0xddd5', 16)

print(num) #=> 56789
# Python 2.6+
num = int('0Xddd5', 16)

print(num) #=> 56789

Specifying an invalid hexadecimal number would raise the following error:

// ValueError: invalid literal for int() with base 16: '0o30071'
int('0o30071', 16)

If the hexadecimal string has 0x (or 0X) radix prefix, then you may also specify 0 as the second argument (i.e. the base) to the int() method, which would make it infer the value:

# Python 2.6+
num = int('0xddd5', 0)

print(num) #=> 56789

This could be useful, for example, if a variable with a number can be of different types (such as binary, octal, hexadecimal, etc.).


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.