Home » Decimal to Hexadecimal in Python

Decimal to Hexadecimal in Python

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 :

HexadecimalDecimalBinary
A101010
B111011
C121100
101610000
111710001
121810010
Conversion table

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