Python program to convert hex string to decimal

Converting hexadecimal strings to decimal numbers is a common programming task. Python provides multiple approaches to handle this conversion using built-in functions and modules.

What is Hexadecimal?

Hexadecimal is a base-16 number system using digits 0-9 and letters A-F (representing values 10-15). For example, hex 'F' equals decimal 15, and hex '1A' equals decimal 26.

Using int() Function

The most straightforward method uses Python's built-in int() function with base 16 ?

# Single hex digit
hex_string = 'F'
decimal_result = int(hex_string, 16)
print(f"Hex '{hex_string}' = Decimal {decimal_result}")

# Multi-digit hex string
hex_string = '1A3'
decimal_result = int(hex_string, 16)
print(f"Hex '{hex_string}' = Decimal {decimal_result}")

# Hex with mixed case
hex_string = 'AbC'
decimal_result = int(hex_string, 16)
print(f"Hex '{hex_string}' = Decimal {decimal_result}")
Hex 'F' = Decimal 15
Hex '1A3' = Decimal 419
Hex 'AbC' = Decimal 2748

Using ast.literal_eval()

For hex strings prefixed with '0x', use the ast.literal_eval() function which safely evaluates literal expressions ?

from ast import literal_eval

# Hex string with 0x prefix
hex_string = '0xF'
decimal_result = literal_eval(hex_string)
print(f"Hex '{hex_string}' = Decimal {decimal_result}")

# Larger hex number with prefix
hex_string = '0x1A3'
decimal_result = literal_eval(hex_string)
print(f"Hex '{hex_string}' = Decimal {decimal_result}")
Hex '0xF' = Decimal 15
Hex '0x1A3' = Decimal 419

Handling Different Input Formats

Create a flexible function that handles both prefixed and non-prefixed hex strings ?

def hex_to_decimal(hex_string):
    """Convert hex string to decimal, handling different formats."""
    # Remove whitespace and convert to lowercase
    hex_string = hex_string.strip().lower()
    
    # Handle 0x prefix
    if hex_string.startswith('0x'):
        return int(hex_string, 16)
    else:
        return int(hex_string, 16)

# Test different formats
test_cases = ['F', '0xF', '1a3', '0X1A3', '  ABC  ']

for hex_val in test_cases:
    decimal_val = hex_to_decimal(hex_val)
    print(f"'{hex_val}' ? {decimal_val}")
'F' ? 15
'0xF' ? 15
'1a3' ? 419
'0X1A3' ? 419
'  ABC  ' ? 2748

Error Handling

Handle invalid hex strings gracefully using try-except blocks ?

def safe_hex_to_decimal(hex_string):
    """Safely convert hex to decimal with error handling."""
    try:
        # Remove whitespace and handle prefix
        cleaned = hex_string.strip().lower()
        if cleaned.startswith('0x'):
            return int(cleaned, 16)
        else:
            return int(cleaned, 16)
    except ValueError:
        return f"Error: '{hex_string}' is not a valid hex string"

# Test with valid and invalid inputs
test_cases = ['FF', '0xABC', 'GHI', '123', 'XYZ']

for hex_val in test_cases:
    result = safe_hex_to_decimal(hex_val)
    print(f"'{hex_val}' ? {result}")
'FF' ? 255
'0xABC' ? 2748
'GHI' ? Error: 'GHI' is not a valid hex string
'123' ? 291
'XYZ' ? Error: 'XYZ' is not a valid hex string

Comparison

Method Input Format Best For
int(string, 16) No prefix required Simple conversion, most flexible
ast.literal_eval() Requires '0x' prefix When hex strings include prefix

Conclusion

Use int(hex_string, 16) for most hex-to-decimal conversions as it's simple and handles various formats. The ast.literal_eval() method works specifically with '0x' prefixed strings and provides additional safety for evaluating literal expressions.

Updated on: 2026-03-25T06:59:26+05:30

629 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements