Python program to convert hex string to decimal

PythonServer Side ProgrammingProgramming

In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given a hexadecimal string, we need to convert it into its decimal equivalent.

We have two approaches to solve the problem−

  • Brute-force Approach
  • Using Built-in module

Brute-Force Method

Here we take the help of explicit type casting function i.e. integer. This function takes two arguments i.e. hex equivalent and base i.e. (16). This function is used to convert a hexadecimal string to its equivalent decimal in an integer type, which can be further typecasted back to string format.

Example

 Live Demo

#input string
string = 'F'
# converting hexadecimal string to decimal
res = int(string, 16)
# print result
print("The decimal number associated with hexadecimal string is : " + str(res))

Output

The decimal number associated with hexadecimal string is: 15

Using Built-In “ast” module

Here we use literal_eval function available in ast module, we can predict the base of given hexadecimal equivalent and then convert into its decimal equivalent. Here we use the concept of literal evaluation.

Example

 Live Demo

# using built-in module literal_eval
from ast import literal_eval
# initializing string
test_string = '0xF'
# converting hexadecimal string to decimal
res = literal_eval(test_string)
# print result
print("The decimal number of the hexadecimal string is : " + str(res))

Output

The decimal number of the hexadecimal string is: 15

All the variables are declared in the local scope and their references are seen in the figure above.

Conclusion

In this article, we have learned about converting given hex string into the decimal equivalent.

raja
Published on 23-Dec-2019 12:04:00
Advertisements