Summary: In this programming example, we will learn how to convert a decimal to hexadecimal in Python using hex(), loop, and recursion.

Convert Decimal to Hexadecimal using the hex() method

Python hex() is an inbuilt method that converts an integer to its corresponding hexadecimal form.

hex() returns hexadecimal in the form of string prefixed with 0x.

Example:

decimal = int(input("Enter a number: "))
print("Hexadecimal: ",hex(decimal))
Enter a number: 20
Hexadecimal: 0x14


Here the prefix 0x in the output indicates that the number 14 is in hexadecimal form.

Convert Decimal to Hexadecimal using Loop

The standard mathematical way to convert a decimal to hexadecimal is to divide the number by 16 until it reduces to zero.

The sequence of remainders from last to first in hex form is the hexadecimal form of the given decimal number.

The following conversion table is used to convert remainders into hex form:

RemainderHexRemainderHex
0010A
1111B
2212C
3313D
4414E
5515F
66
77
88
99
Hexadecimal Conversion Table

Example:

Decimal to Hexadecimal
Decimal to Hexadecimal

Here is the implementation of the same in Python using while loop:

conversion_table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A' , 'B', 'C', 'D', 'E', 'F']

decimal = int(input("Enter a number: "))
hexadecimal = ''

while(decimal>0):
    remainder = decimal%16
    hexadecimal = conversion_table[remainder]+ hexadecimal
    decimal = decimal//16
    
print("Hexadecimal: ",hexadecimal)
Enter a number: 44
Hexadecimal: 2C


In this program, inside the while loop, we divide the decimal number until it reduces to zero and simultaneously concatenate the hex form of the remainder to the hexadecimal string using the conversion_table list .

Convert Decimal to Hexadecimal using Recursion

The division method of converting a decimal number to hexadecimal can also be implemented using recursion.

conversion_table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A' , 'B', 'C', 'D', 'E', 'F']

def decTohex(n):
    if(n<=0):
        return ''
    remainder = n%16
    return  decTohex(n//16)+conversion_table[remainder]
        
decimal = int(input("Enter a number: "))
print("Hexadecimal: ",decTohex(decimal))
Enter a number: 205
Hexadecimal: CD


In this program, the base condition of the recursive function is n<=0. For any positive decimal number the recursive calls stops when the remainder hits zero.

After the recursive process, the hex form of the remainder gets concatenated in last to first fashion and is returned to the calling statement.

In this tutorial, we learned multiple ways to convert a decimal number to its corresponding hexadecimal form in Python programming language.

This Post Has 2 Comments

  1. Praneeth

    If we have input as -1 how to do?

    1. Adarsh Kumar

      Extract the digits using int(str(decimal)[1:], use the code to transform it into hexadecimal and finally prepend back the negative (-) to the result.

Leave a Reply