Hexadecimal To Decimal In Python

Hexadecimal To Decimal In Python

Published on September 05 2023

In this tutorial you will see how to convert hexadecimal numbers into decimal using logical implementation. Also, we will use built in methods and understand each line in detail.

Source code

hexa_value = input("Enter any hexa value - Only allowed 0-9 and A-F:").strip().upper()

# Method - 1 - Using Custom Logic
def hexa_to_decimal(hexValue):
    conversion_table = {
        '0': 0, '1': 1, '2': 2, '3': 3,
        '4': 4, '5': 5, '6': 6, '7': 7,
        '8': 8, '9': 9, 'A': 10, 'B': 11,
        'C': 12, 'D': 13, 'E': 14, 'F': 15
    }
    position = len(hexValue) - 1
    decimal_number = 0

    for x in hexValue:
        decimal_number = decimal_number + conversion_table[x] * pow(16, position)
        position = position - 1

    return decimal_number

output = hexa_to_decimal(hexa_value)
print('Decimal value:', output)


# Method - 2 - Using Built In Method - int()
output = int(hexa_value, 16)
print('Decimal value:', output)