
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to convert hex string to decimal
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
#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
# 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.
- Related Articles
- How to Convert Hex String to Hex Number in C#?
- How to convert hex string into int in Python?
- How to Convert Hex Numbers to Decimal Numbers in Excel?
- Convert Integer to Hex String in Java
- Convert hex string to number in MySQL?
- 8085 Program to convert ASCII to HEX
- 8085 Program to convert HEX to ASCII
- 8085 Program to convert BCD to HEX
- 8085 Program to convert HEX to BCD
- Python program to convert decimal to binary number
- How to convert Int to Hex String in Kotlin?
- Convert byte Array to Hex String in Java
- Convert Hex String to byte Array in Java
- Python program to print decimal octal hex and binary of first n numbers
- Python program to convert float decimal to octal number
