Convert a hex string to an integer in Python
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:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "0x64" # With 0x prefix x = int(s, 16) print(x) # 100 |
This also works without the 0x prefix:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "64" # Without 0x prefix x = int(s, 16) print(x) # 100 |
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "0x64" # With 0x prefix x = int(s, 0) print(x) # 100 |
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:
|
1 2 3 4 5 6 7 8 9 |
import ast if __name__ == '__main__': s = "0x64" x = ast.literal_eval(s) print(x) # 100 |
That’s all about converting a hex string to an integer in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)