DEV Community

Abhay Singh
Abhay Singh

Posted on

Converting Decimal to Hexadecimal in Python

def decimal_to_hexadecimal(decimal_number):
    if decimal_number < 0:
        raise ValueError("Input must be a non-negative integer.")

    # Convert decimal to hexadecimal
    hexadecimal_number = hex(decimal_number)

    # Remove the '0x' prefix and return the result in uppercase
    return hexadecimal_number[2:].upper()

# Example usage
if __name__ == "__main__":
    try:
        decimal_input = int(input("Enter a non-negative decimal number: "))
        hex_output = decimal_to_hexadecimal(decimal_input)
        print(f"The hexadecimal representation of {decimal_input} is: {hex_output}")
    except ValueError as e:
        print(f"Error: {e}")
Enter fullscreen mode Exit fullscreen mode

Explanation of the Code
Function Definition: The function decimal_to_hexadecimal takes a single argument, decimal_number.
Input Validation: It checks if the input is a non-negative integer. If not, it raises a ValueError.
Conversion: The built-in hex() function converts the decimal number to hexadecimal. The result includes a '0x' prefix, which is removed by slicing the string.
Output Formatting: The resulting hexadecimal string is converted to uppercase for consistency.
Example Usage: The script prompts the user for input and displays the hexadecimal representation.

Top comments (0)