Program for Decimal to Hexadecimal Conversion in Python
Decimal to Hexadecimal Conversion
Converting a decimal number to hexadecimal involves dividing the number by 16 and recording the remainder.
We will explore three methods to perform this conversion using Python programming.
Method 1: Using Built-in Function
We use Python's built-in function to convert decimal to hexadecimal.
decimal = int(input("Enter a decimal number: ")) print("Hexadecimal:", hex(decimal)[2:].upper())
Output:
Enter a decimal number: 255 Hexadecimal: FF
Method 2: Using Division by 16
We repeatedly divide the decimal number by 16 and store the remainders to get the hexadecimal equivalent.
def decimal_to_hexadecimal(decimal): hex_digits = "0123456789ABCDEF" hex_number = "" while decimal > 0: remainder = decimal % 16 hex_number = hex_digits[remainder] + hex_number decimal //= 16 return hex_number decimal = int(input("Enter a decimal number: ")) print("Hexadecimal:", decimal_to_hexadecimal(decimal) if decimal != 0 else "0")
Output:
Enter a decimal number: 255 Hexadecimal: FF
Method 3: Using Recursion
We use recursion to convert decimal to hexadecimal.
def decimal_to_hexadecimal_recursive(decimal): if decimal == 0: return "" hex_digits = "0123456789ABCDEF" return decimal_to_hexadecimal_recursive(decimal // 16) + hex_digits[decimal % 16] decimal = int(input("Enter a decimal number: ")) hexadecimal = decimal_to_hexadecimal_recursive(decimal) print("Hexadecimal:", hexadecimal if hexadecimal else "0")
Output:
Enter a decimal number: 255 Hexadecimal: FF