Convert Decimal to Hexadecimal

Theory:

Decimal to hexadecimal conversion involves dividing the decimal number by 16 repeatedly and noting down the remainders. The remainders, in reverse order, represent the hexadecimal equivalent of the decimal number.

Python Code:

def decimal_to_hexadecimal(decimal):
    hexadecimal_chars = "0123456789ABCDEF"
    if decimal < 0:
        return "Negative decimal numbers cannot be represented in hexadecimal."
    elif decimal == 0:
        return "0"
    else:
        hexadecimal = ""
        while decimal > 0:
            remainder = decimal % 16
            hexadecimal = hexadecimal_chars[remainder] + hexadecimal
            decimal //= 16
        return hexadecimal

# Taking input from the user
decimal_number = int(input("Enter a decimal number to convert to hexadecimal: "))
print("Hexadecimal equivalent:", decimal_to_hexadecimal(decimal_number))

Example:

Enter a decimal number to convert to hexadecimal: 255

Hexadecimal equivalent: FF

Code Explanation:

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

If the input is negative, the function returns an error message. If it's zero, it returns "0". Otherwise, it repeatedly divides the decimal number by 16, notes down the remainders, and constructs the hexadecimal representation.

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