Python Program to Convert Hexadecimal to Decimal

python programs

Summary: In this programming example, we will learn to convert hexadecimal to Decimal in Python using int() and loop.

Convert Hexadecimal to Decimal using int()

We can easily convert any hexadecimal number to decimal by using the built-in int() function in Python.

The int() function converts the specified hexadecimal number prefixed with 0x to an integer of base 10.

If the hexadecimal number is in the string format then the second parameter is required to identify the base of the specified number in string format.

In that case, we pass 16 as the second parameter value to the int() function.

Example:

print(int(0xA))      #output 10
print(int(0xff))     #output 255

print(int('A', 16))  #output 10
print(int('ff', 16)) #output 255

The best practice is to always specify the second parameter as 16 whether we are specifying hexadecimal prefixed with 0x or in the string format.

Convert Hexadecimal to Decimal without int()

The standard mathematical way to convert hexadecimal to decimal is to multiply each digit of the hexadecimal number with its corresponding power of 16 and sum them.

Decimal = dn-1×16n-1 + … + d3×163 + d2×162 + d1×161+ d0×160

The following conversion table is used to transform hex digits such as A, B, C, etc to their decimal representation.

HexDecimalHexDecimal
00A10
11B11
22C12
33D13
44E14
55F15
66
77
88
99
Hexadecimal Conversion Table

Example:

We can implement the same in Python using for loop and without using the int() function.

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}

hexadecimal = input("Enter the hexadecimal number: ").strip().upper()
decimal = 0

#computing max power value
power = len(hexadecimal) -1

for digit in hexadecimal:
    decimal += conversion_table[digit]*16**power
    power -= 1
    
print(decimal)

Enter the hexadecimal number: ff
255

In this program, we have used strip() method to trim any leading or trailing whitespace in the input value.

The upper() method transforms the input string to its upper case value so that the characters match the dictionary’s key without any case ambiguity.

Using for loop we traverse the hexadecimal string and convert the hex digit to its corresponding decimal form using the conversion table.

We then multiply each digit with its corresponding power of 16 and add them to the decimal variable.

In this tutorial, we learned multiple ways to convert hexadecimal numbers to their corresponding decimal value in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *