Iterative Approach

The conventional method for converting decimal to hexadecimal is to divide it by 16 until it equals zero. The hexadecimal version of the given decimal number is the sequence of remainders from last to first in hexadecimal form. To convert remainders to hexadecimal form, use the following conversion table:

Remainder Hex Equivalent
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 A
11 B
12 C
13 D
14 E
15 F

Code :

Python3




# Conversion table of remainders to
# hexadecimal equivalent
conversion_table = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4',
                    5: '5', 6: '6', 7: '7',
                    8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C',
                    13: 'D', 14: 'E', 15: 'F'}
  
  
# function which converts decimal value
# to hexadecimal value
def decimalToHexadecimal(decimal):
    hexadecimal = ''
    while(decimal > 0):
        remainder = decimal % 16
        hexadecimal = conversion_table[remainder] + hexadecimal
        decimal = decimal // 16
  
    return hexadecimal
  
  
decimal_number = 69
print("The hexadecimal form of", decimal_number,
      "is", decimalToHexadecimal(decimal_number))


Output:

The hexadecimal form of 69 is 45

Python Program to Convert Decimal to Hexadecimal

In this article, we will learn how to convert a decimal value(base 10) to a hexadecimal value (base 16) in Python. 

Similar Reads

Method 1: Using hex() function

hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form....

Method 2: Iterative Approach

...

Method 3: Recursive Approach

The conventional method for converting decimal to hexadecimal is to divide it by 16 until it equals zero. The hexadecimal version of the given decimal number is the sequence of remainders from last to first in hexadecimal form. To convert remainders to hexadecimal form, use the following conversion table:...