SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
5.recursion
Exercise:
Programming Excercises
Question:22 | ISBN:978013274719 | Edition: 6

Question

(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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.