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
Numbers

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

HCF - Highest Common Factor: C C++ Java Python

LCM - Lowest Common Multiple: C C++ Java Python

GCD - Greatest Common Divisor: C C++ Java Python

Binary to Decimal Conversion: C C++ Java Python

Octal to Decimal Conversion: C C++ Java Python

Hexadecimal to Decimal Conversion: C C++ Java Python

Decimal to Binary Conversion: C C++ Java Python

Decimal to Octal Conversion: C C++ Java Python

Decimal to Hexadecimal Conversion: C C++ Java Python

Binary to Octal Conversion: C C++ Java Python

Quadrants in which a given coordinate lies: C C++ Java Python

Addition of Two Fractions: C C++ Java Python

Calculate the Area of a Circle: C C++ Java Python

Convert Digit/Number to Words: C C++ Java Python

Finding Roots of a Quadratic Equation: C C++ Java Python