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:

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:

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.

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.

Leave a Reply