(Decimal to hex) Write a recursive function that converts a decimal number into a hex number as a string. The function header is as follows:
def decimalToHex(value):
Write a test program that prompts the user to enter a decimal number and displays its hex equivalent.
Decimal to hex Conversion Program Code:
#Recursive function 'decimalToHex' accepts an integer parameter, value
#to convert a decimal number to hexadecimal.
def decimalToHex(value):
# Define a dictionary for hexadecimal digits
hex_digits = "0123456789ABCDEF"
# Base case: If the value is less than or equal to 15,
#return the corresponding hexadecimal digit
if value <= 15:
return hex_digits[value]
# Recursive case: Convert the quotient of value divided by 16 to hexadecimal,
# concatenate it with the remainder of value divided by 16, and return the result.
return decimalToHex(value // 16) + hex_digits[value % 16]
# Prompt the user for input
decimal = int(input("Enter a decimal number: "))
# Convert the decimal number to hexadecimal
hexadecimal = decimalToHex(decimal)
# Display the result
print(f"The hexadecimal equivalent of {decimal} is: {hexadecimal}")
Executed Output:
Enter a decimal number: 255
The hexadecimal equivalent of 255 is: FF