Python Decimal to Hexadecimal Conversion Program – This Python tutorial will explain the actual logic to convert a decimal number to corresponding hexadecimal number. It will also explain the important statements of the Python program for conversion of decimal to hexadecimal number.
How to Convert Decimal to Hexadecimal Number
We know that the hexadecimal number system has 0 to 9 digits and A to F letters. The letters A to F represent 10 to 15 in hexadecimal number system. it means that when we divide a decimal number by 16, if the remainder is 10, we will use A in place of 10. Similarly, we use B for 11, C for 12, D for 13, E for 14 and F for 15.
Procedure to Convert Decimal into Hexadecimal
- We will divide the given decimal number by 16, and get quotient1 and remainder1. For example, divide decimal 225 by 16, quotient1=14 and remainder1=1
- Divide quotient1=14 by 16 and get quotient and remainder, so quotient2=0 and remainder2=14 Note that we will represent 14 by E in hexadecimal number system.
- We will repeat step 2 until the quotient is zero. Since the quotient is zero in above step so , we stop and write remainders in reverse order , which is E1. It means that the decimal number 225 is equal to hexadecimal number=E1.
The Source Code of Python Decimal to Hexadecimal Conversion Program
# This Python script / program is used to input # a decimal number and convert into hexa decimal number # using a while loop # author: www.EasyCodeBook.com (c) num = int(input('Enter a Decimal number to Convert into Hexa decimal:')) q=num # define a list to store digits of hexa decimal number # since hexa decimal also conatains A, B, C, D, E, and F # in place of 10,11, 12,13,14,and 15 hexa = [] while q!=0: rem = q % 16 if rem>9: hexa.append(chr(rem+55)) else: hexa.append(chr(rem+48)) q = q // 16 print('Hexa decimal Number =',end='') for j in reversed(hexa): print(j,end='')
The output of the Python Program is as follows:
Enter a Decimal number to Convert into Hexa decimal:225
Hexa decimal Number =E1
The Logic behind important statemnts in Python Program
if rem>9: hexa.append(chr(rem+55)) else: hexa.append(chr(rem+48))
If remainder is 0 to 9 then we use chr(rem+48) function. For example if rem=1 then it becomes chr(1+48). Hence chr(49) will return 1 as character. So we are converting integer to character by using chr() function. We know that 49 is ascii character of 1. But if remainder is greater than 9, suppose it is 10. Then we must use A in place of 10. We know that ascii code of A is 65. So we add 55 in remainder 10 to get 65. Now we applu chr(rem+55) that is chr(65) to get character of A. And these converted characters are stored in our list named hexa. We use append() function to insert an item at the end of a list.
Therefore all remainders will be in the list. Now we will display the list in reverse order since we need remainders in reverse order. Hence we use a Python builtin function reversed(hexa) to reverse the list for displaying.