Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about Python Program To Convert Hexadecimal To Decimal.
Code For Python Program To Convert Hexadecimal To Decimal
def hex_to_decimal(num):
decimal = int(num, 16)
return decimal
# Test the function
print(hex_to_decimal("A"))
Output
10
Explanation
The program defines a function hex_to_decimal
that takes an hexadecimal string as an argument (num
). Inside the function, it uses the built-in int()
function with base=16
to convert the hexadecimal string to its decimal representation.
You can test the function by calling it with any hexadecimal string as an argument, as shown in the last line of the code. This will print out the decimal representation of the hexadecimal number.
Another way to convert Hexadecimal to decimal is by looping through the string and multiplying each digit by its corresponding power of 16:
def hex_to_decimal(num):
decimal = 0
for index, digit in enumerate(num[::-1]):
decimal += int(digit, 16) * (16 ** index)
return decimal
# Test the function
print(hex_to_decimal("A"))
This method will also give the same result as the first one.
Python Program To Convert Decimal To Binary
Conclusion
Both the above methods will work and give the same result, you can choose the one you are more comfortable with.