Home » Hexadecimal to Decimal in Python

Hexadecimal to Decimal in Python

Learn about Hexadecimal to Decimal in Python in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.


Hexadecimal to Decimal in Python

This function can be used to execute this operation; by passing an argument (16), it can convert a hexadecimal string number to base sixteen while also converting it to an integer.

# Python program to convert hexadecimal to decimal

def HexDecimal(n):
    return int(n, 16)
# input
num = input('Enter hexadecimal number: ')

# function call
print('The decimal value is =', HexDecimal(num))


Enter hexadecimal number: C
The decimal value is = 12

Using ast.literal_eval() :

This function can be performed by utilising a literal evaluation function that estimates the base and converts the number string to decimal number format.

# Python program for converting hexadecimal string to decimal

from ast import literal_eval

# string
test_string = input('Enter string :')

# using ast.literal_eval()
res = literal_eval(test_string)

# print result
print("The decimal number of hexadecimal string : " + str(res))


Enter string :0XC
The decimal number of hexadecimal string : 12

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Similar Code : Python program to convert decimal to hexadecimal