Hexadecimal to Decimal Conversion in Python
Hexadecimal to Decimal Conversion
Hexadecimal to Decimal conversion is the process of converting a hexadecimal number (base-16) into its equivalent decimal number (base-10). Each hexadecimal digit represents a power of 16.
For example, the hexadecimal number 1F is equal to decimal 31 because:
(1 × 16¹) + (F × 16⁰) = 16 + 15 = 31
We will explore three methods to convert a hexadecimal number to a decimal number using Python programming.
Method 1: Using Loop
We extract each digit of the hexadecimal number, multiply it by the corresponding power of 16, and sum the results.
def hex_to_decimal(hex_str): decimal = 0 length = len(hex_str) for i in range(length): if '0' <= hex_str[i] <= '9': value = ord(hex_str[i]) - ord('0') else: value = ord(hex_str[i]) - ord('A') + 10 decimal += value * (16 ** (length - i - 1)) return decimal hex_str = input("Enter a hexadecimal number: ").upper() print("Decimal equivalent:", hex_to_decimal(hex_str))
Output:
Enter a hexadecimal number: 1F Decimal equivalent: 31
Method 2: Using Built-in Function
We can use Python's int() function to directly convert a hexadecimal number to a decimal number.
hex_str = input("Enter a hexadecimal number: ").upper() decimal = int(hex_str, 16) print("Decimal equivalent:", decimal)
Output:
Enter a hexadecimal number: 1F Decimal equivalent: 31
Method 3: Using Recursion
We recursively extract each digit and multiply it by the corresponding power of 16.
def hex_to_decimal_recursive(hex_str, length, index=0): if index == length: return 0 if '0' <= hex_str[index] <= '9': value = ord(hex_str[index]) - ord('0') else: value = ord(hex_str[index]) - ord('A') + 10 return value * (16 ** (length - index - 1)) + hex_to_decimal_recursive(hex_str, length, index + 1) hex_str = input("Enter a hexadecimal number: ").upper() print("Decimal equivalent:", hex_to_decimal_recursive(hex_str, len(hex_str)))
Output:
Enter a hexadecimal number: 1F Decimal equivalent: 31