(Hex to decimal) Write a recursive function that parses a hex number as a string into a decimal integer. The function header is as follows:
def hexToDecimal(hexString):
Write a test program that prompts the user to enter a hex string and displays its decimal equivalent.
Hex to decimal Program code:
#The recursive function hexToDecimal accepts a string and
#convert decimal conversion
def hexToDecimal(hexString):
# Base case: if the hex string is empty, return 0
if hexString == "":
return 0
# Get the last character from the hex string
lastChar = hexString[-1]
# Convert the last character to decimal
if lastChar.isdigit():
decimalValue = int(lastChar)
else:
decimalValue = ord(lastChar.upper()) - ord('A') + 10
# Recursive call to process the remaining characters
remainDecimalValue = hexToDecimal(hexString[:-1])
# Calculate the decimal value by multiplying
#the digit with 16 raised to the power of its position
result = decimalValue * (16 ** len(hexString[:-1]))
# Add the decimal value of the last character
#to the remaining decimal
result += remainDecimalValue
return result
# Test program
hex_string = input("Enter a hex string: ")
# Call the hexToDecimal function with the input hex string
result = hexToDecimal(hex_string)
# Display the decimal equivalent
print("Decimal equivalent:", result)
Executed Output:
Enter a hex string: FF
Decimal equivalent: 255