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()

int() function can be used to convert hexadecimal to decimal in Python.

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, pass 16 as second parameter value to the int() function.

Example:

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 digit such as A, B, C, etc to its 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 int() method.

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 matches the dictionary’s key without any case ambiguity.

Using for loop we traverse the hexadecimal string, 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 number to its corresponding decimal value in Python.

Leave a Reply