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:
Remainder | Hex | Remainder | Hex |
---|---|---|---|
0 | 0 | 10 | A |
1 | 1 | 11 | B |
2 | 2 | 12 | C |
3 | 3 | 13 | D |
4 | 4 | 14 | E |
5 | 5 | 15 | F |
6 | 6 | ||
7 | 7 | ||
8 | 8 | ||
9 | 9 |
Example:
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.
If we have input as -1 how to do?
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.