convert hexadecimal string to integer in python

Python – Convert Hexadecimal String to Integer

In this tutorial, we will look at how to convert a hexadecimal number (as a string) to an integer in Python with the help of examples.

How to convert hexadecimal string to integer in Python?

convert hexadecimal string to integer in python

You can use the Python built-in int() function to convert a hexadecimal string to an integer in Python. Pass the hex string as an argument. The following is the syntax –

# hex string to int
int(hex_str, 16)

The int() function also takes an optional argument, base to identify the base of the value passed. For example, use 16 as the base to convert hex string, use 8 as the base for an octal string, etc.

Although, the int() function is capable of inferring the base from the string passed, it’s a good practice to explicitly specify the base.

Examples

Let’s look at some examples of using the above syntax to convert a hex string to an int.

Hex string with prefix to int

Let’s convert a hex string with the prefix '0x' to an integer using the int() function.

# hex string representing 1024
hex_str = '0x400'
# hex to int
num = int(hex_str, 16)
print(num)

Output:

1024

Here we have a hex string representing the number 1024 with the prefix '0x'. We use the int() function to convert the hex string to an integer. You can see that we get 1024 as the output.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Hex string without prefix to int

Let’s now try to convert a hex string without a prefix to int using the int() function. You don’t need to change any arguments as the int() function is capable to handle the hex string irrespective of the presence of the prefix.

# hex string representing 1024 without '0x' prefix
hex_str = '400'
# hex to int
num = int(hex_str, 16)
print(num)

Output:

1024

Here we pass the hex string without the '0x' prefix to the int() function with base as 16. We get the same output as above.

For more on the Python int() function, refer to its documentation.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top