Learn about Decimal to Hexadecimal in Python in the below code example. Also, refer to the comments in the code snippet to get a detailed view of what’s actually happening.
Contents
Decimal to Hexadecimal in Python
The hex() method in Python is used to convert decimal integers to hexadecimal integers as a string.
- You may be aware that binary is a base 2 system (0,1).
- A decimal number is a number with a base of 10 (0,1,2,3,4,5,6,7,8,9).
- A hexadecimal is a base 16 number (0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F).
In a computer, they are simply multiple ways of encoding the same number. Look at the table below :
Hexadecimal | Decimal | Binary |
---|---|---|
A | 10 | 1010 |
B | 11 | 1011 |
C | 12 | 1100 |
10 | 16 | 10000 |
11 | 17 | 10001 |
12 | 18 | 10010 |
The syntax for hexadecimal integer is:
hex(x)
where x is decimal number.
Program :
# Python program to convert decimal to hexadecimal
# input
num = int(input('Enter a decimal number: '))
# print result
print('HexaDecimal value = ', hex(num))
Output:
Enter a decimal number: 15
HexaDecimal value = 0xf
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : convert octal to decimal using int() in Python