Python Tutorials

Python Programs

Python Convert Decimal to Hexadecimal


Python Convert Decimal to Hexadecimal

In this tutorial, we will learn how to convert a decimal number to hexadecimal in Python. We will cover the basic concept of hexadecimal numbers and implement a function to perform the conversion.


What is Hexadecimal Conversion

Hexadecimal conversion is the process of converting a decimal (base-10) number to a hexadecimal (base-16) number. In hexadecimal, numbers are represented using digits from 0 to 9 and letters from A to F.


Syntax

The syntax to convert a decimal number to hexadecimal in Python is:

def decimal_to_hexadecimal(n):
    return hex(n).replace('0x', '').upper()


Converting a decimal number to hexadecimal

We can create a function to convert a given decimal number to hexadecimal using Python's built-in functions.

For example,

  1. Define a function named decimal_to_hexadecimal that takes one parameter n.
  2. Use the built-in hex function to convert the decimal number to hexadecimal.
  3. Remove the '0x' prefix from the hexadecimal representation using the replace method.
  4. Convert the result to uppercase for standard hexadecimal notation.
  5. Return the hexadecimal representation as a string.
  6. Call the function with a sample number and print the result.

Python Program

def decimal_to_hexadecimal(n):
    return hex(n).replace('0x', '').upper()

# Convert 255 to hexadecimal
result = decimal_to_hexadecimal(255)

# Print the result
print('Hexadecimal representation of 255 is', result)

Output

Hexadecimal representation of 255 is FF