This post will discuss how to convert a hex string to an integer in Python.

1. Using int constructor

The int constructor int() can be used for conversion between a hex string and an integer. The int constructor takes the string and the base you are converting from. The following program demonstrates this:

Download  Run Code

 
This also works without the 0x prefix:

Download  Run Code

 
If the base of 0 is specified, we’ll infer the base from the string’s prefix. To distinguish between the hex string and decimal string, prefix your string with 0x.

Download  Run Code

2. Using ast.literal_eval() function

Another option is to use the ast.literal_eval() function to evaluate strings safely, as shown below. Note this won’t work without the 0x prefix:

Download  Run Code

That’s all about converting a hex string to an integer in Python.