In this article, we will learn how to convert a decimal value(base 10) to a hexadecimal value (base 16) in Python.
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.
Syntax : hex(x)
Parameters :
- x – an integer number (int object)
Returns : Returns hexadecimal string.
Errors and Exceptions :
TypeError : Returns TypeError when anything other than
integer type constants are passed as parameters.
Code :
Python3
# Python3 program to illustrate # hex() function print ( "The hexadecimal form of 69 is " + hex ( 69 )) |
Output:
The hexadecimal form of 69 is 0x45
Method 2: 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
Method 3: Recursive Approach
The idea is similar to that used in the iterative approach.
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): if (decimal < = 0 ): return '' remainder = decimal % 16 return decimalToHexadecimal(decimal / / 16 ) + conversion_table[remainder] decimal_number = 69 print ( "The hexadecimal form of" , decimal_number, "is" , decimalToHexadecimal(decimal_number)) |
Output:
The hexadecimal form of 69 is 45
Method: Using format specifier
Python3
n = 69 # Here 69 is the number to be converted into hexadecimal value # now we use 'd' for decimal, 'o' for octal, 'x' for hexadecimal as format specifier to format a number # the result is in type of "String" but you can typecaste using int() if necessary print ( '{0:x}' . format (n)) |
45