Skip to main content

How to convert a number from decimal to hexadecimal in Python

How to convert a number from decimal to hexadecimal in Python.

Here's a step-by-step tutorial on how to convert a number from decimal to hexadecimal in Python:

Step 1: Understanding decimal and hexadecimal numbers

  • Decimal numbers are base-10 numbers that we typically use in our day-to-day life.
  • Hexadecimal numbers are base-16 numbers that use digits from 0 to 9 and letters A to F. In hexadecimal, the numbers 10 to 15 are represented as A, B, C, D, E, and F respectively.

Step 2: Converting decimal to hexadecimal using built-in functions

  • Python provides built-in functions to directly convert decimal numbers to hexadecimal.
  • The hex() function takes a decimal number as input and returns its hexadecimal representation.

Example 1: Using hex() function

decimal_number = 255
hex_number = hex(decimal_number)
print(hex_number) # Output: 0xff

Step 3: Converting decimal to hexadecimal manually

  • If you want to perform the conversion manually without using built-in functions, you can follow the steps below.

Step 3.1: Divide the decimal number by 16 and note down the remainder.

  • The remainder will be a digit in the hexadecimal representation.

Example 2: Finding the remainder

decimal_number = 255
remainder = decimal_number % 16
print(remainder) # Output: 15

Step 3.2: Divide the decimal number by 16 again and update the quotient.

  • Repeat this step until the quotient becomes zero.

Example 3: Finding the quotient

decimal_number = 255
quotient = decimal_number // 16
print(quotient) # Output: 15

Step 3.3: Convert the remainder from step 3.1 to its corresponding hexadecimal digit.

  • If the remainder is less than 10, it will remain the same.
  • If the remainder is 10, its hexadecimal digit representation will be 'A'. Similarly, for 11, it will be 'B', and so on.

Example 4: Converting remainder to hexadecimal digit

remainder = 15
hex_digit = str(remainder) if remainder < 10 else chr(remainder + 55)
print(hex_digit) # Output: 'F'

Step 3.4: Continue the steps from 3.1 to 3.3 until the quotient becomes zero.

  • Concatenate the hexadecimal digits obtained in each step to get the final hexadecimal representation.

Example 5: Converting decimal to hexadecimal manually

decimal_number = 255
hexadecimal_digits = []
while decimal_number > 0:
remainder = decimal_number % 16
hex_digit = str(remainder) if remainder < 10 else chr(remainder + 55)
hexadecimal_digits.append(hex_digit)
decimal_number //= 16

hexadecimal_digits.reverse() # Reverse the digits
hex_number = ''.join(hexadecimal_digits)
print(hex_number) # Output: 'FF'

That's it! You've learned how to convert a decimal number to hexadecimal using both built-in functions and manual calculations in Python.