October 13, 2024

Python Program to Convert Hexadecimal String to Decimal String

To convert a hexadecimal string to a decimal string in Python, you can use built-in functions such as int() for conversion and str() to get the decimal representation as a string. Here is a simple Python program to achieve this:

1. Example Program

# Function to convert hexadecimal string to decimal string
def hex_to_decimal(hex_string):
    try:
        # Convert hex string to an integer (base 16)
        decimal_value = int(hex_string, 16)
        # Convert the integer to a string
        decimal_string = str(decimal_value)
        return decimal_string
    except ValueError:
        return "Invalid hexadecimal string"

# Example usage
hex_string = '1a3f'
decimal_string = hex_to_decimal(hex_string)
print(f'Hexadecimal: {hex_string}')
print(f'Decimal: {decimal_string}')
    

2. Explanation

The hex_to_decimal function performs the following steps:

  • Conversion: The int(hex_string, 16) function converts the hexadecimal string to a decimal integer. The second argument, 16, specifies the base of the input number system (hexadecimal).
  • String Conversion: The str(decimal_value) function converts the decimal integer to a string.
  • Error Handling: If the input string is not a valid hexadecimal number, the function returns “Invalid hexadecimal string” to handle any potential errors.

3. Output

When you run the example program with the hexadecimal string '1a3f', the output will be:

Hexadecimal: 1a3f
Decimal: 6719
    

4. Conclusion

Converting a hexadecimal string to a decimal string in Python is straightforward using the int() function. This method can be easily adapted for different use cases where hexadecimal to decimal conversion is needed.