Convert Hexadecimal to Decimal

Theory:

Hexadecimal to decimal conversion involves multiplying each digit of the hexadecimal number with its positional value (powers of 16) and summing them up.

Python Code:

def hexadecimal_to_decimal(hexadecimal):
    hexadecimal = hexadecimal.upper()
    hexadecimal_chars = "0123456789ABCDEF"
    decimal = 0
    for digit in hexadecimal:
        if digit in hexadecimal_chars:
            decimal = 16 * decimal + hexadecimal_chars.index(digit)
        else:
            return "Invalid hexadecimal number."
    return decimal

# Taking input from the user
hexadecimal_number = input("Enter a hexadecimal number to convert to decimal: ")
print("Decimal equivalent:", hexadecimal_to_decimal(hexadecimal_number))

Example:

Enter a hexadecimal number to convert to decimal: FF

Decimal equivalent: 255

Code Explanation:

The function hexadecimal_to_decimal(hexadecimal) takes a hexadecimal number as input and returns its decimal representation.

It first converts the hexadecimal number to uppercase to handle lowercase letters. Then, it iterates through each digit of the hexadecimal number, multiplies it by the positional value (powers of 16), and accumulates the result.

The example usage section demonstrates how to take input from the user, convert the hexadecimal number to decimal, and print the result.