Convert hex string to integer in Python
Categories:
Converting Hexadecimal Strings to Integers in Python

Learn how to efficiently convert hexadecimal string representations into their integer equivalents in Python, covering various methods and common pitfalls.
Python provides straightforward ways to handle conversions between different number bases. One common task is converting a hexadecimal string (e.g., "0xFF"
, "A5"
) into its corresponding integer value. This article will guide you through the primary methods using Python's built-in functions, discuss their nuances, and provide practical examples.
Using the int()
Function for Conversion
The most direct and Pythonic way to convert a hexadecimal string to an integer is by using the built-in int()
function. This function is versatile and can handle conversions from various bases, including hexadecimal. When converting from a hexadecimal string, you need to provide two arguments: the string to convert and the base of the number system, which is 16
for hexadecimal.
hex_string_1 = "FF"
hex_string_2 = "0xFF"
hex_string_3 = "a5"
# Convert without '0x' prefix
int_value_1 = int(hex_string_1, 16)
print(f"'{hex_string_1}' (base 16) -> {int_value_1}")
# Convert with '0x' prefix
int_value_2 = int(hex_string_2, 16)
print(f"'{hex_string_2}' (base 16) -> {int_value_2}")
# Case-insensitivity
int_value_3 = int(hex_string_3, 16)
print(f"'{hex_string_3}' (base 16) -> {int_value_3}")
Basic usage of int()
for hexadecimal string conversion
int()
function is case-insensitive for hexadecimal digits (A-F) and can handle strings both with and without the 0x
or 0X
prefix, as long as the base 16
is explicitly provided.Handling Invalid Hexadecimal Strings
It's crucial to consider how your code will behave when encountering invalid hexadecimal strings. If the input string contains characters that are not valid hexadecimal digits (0-9, A-F, a-f) or an incorrect prefix, the int()
function will raise a ValueError
. Robust applications should include error handling to gracefully manage such situations.
invalid_hex_string_1 = "G1"
invalid_hex_string_2 = "0xFG"
try:
int_value = int(invalid_hex_string_1, 16)
print(f"'{invalid_hex_string_1}' -> {int_value}")
except ValueError as e:
print(f"Error converting '{invalid_hex_string_1}': {e}")
try:
int_value = int(invalid_hex_string_2, 16)
print(f"'{invalid_hex_string_2}' -> {int_value}")
except ValueError as e:
print(f"Error converting '{invalid_hex_string_2}': {e}")
Error handling for invalid hexadecimal strings
flowchart TD A[Start] --> B{Input Hex String?} B -- Valid --> C[Call int(hex_string, 16)] C --> D{Conversion Successful?} D -- Yes --> E[Return Integer] D -- No (ValueError) --> F[Handle Error] B -- Invalid --> F F --> G[End]
Flowchart for converting hexadecimal strings to integers with error handling
Alternative: Using eval()
(Not Recommended)
While eval()
can technically convert hexadecimal strings (if they are valid Python literal representations like 0xFF
), it is generally not recommended for this purpose due to significant security risks. eval()
executes arbitrary Python code, making it a potential vulnerability if the input string comes from an untrusted source. Always prefer int()
for safe and explicit conversions.
# This approach is NOT recommended for untrusted input
hex_literal = "0xFF"
int_value = eval(hex_literal)
print(f"Using eval(): '{hex_literal}' -> {int_value}")
# eval() will fail without the '0x' prefix
try:
eval("FF")
except NameError as e:
print(f"Error using eval() without '0x' prefix: {e}")
Demonstration of eval()
(use with caution)
eval()
with user-provided or untrusted input. It can lead to severe security vulnerabilities by executing malicious code. Stick to int()
for safe hexadecimal conversions.