Converting numbers between different number systems is a common task in programming. One such important conversion is from Decimal (Base-10) to Hexadecimal (Base-16). This is frequently used in computer science, memory addressing, and color codes (like #FF5733), and debugging.
In this article, you’ll learn how to write a Python programs that converts a decimal number to hexadecimal and vice versa using built-in methods and manual logic.
Table of contents
Decimal and Hexadecimal Numbers
Decimal Number (Base-10)
- The decimal system is the standard number system we use every day.
- It uses 10 digits:
0to9. - Each digit’s place value is a power of 10.
347 = ( 3 × 10² ) + ( 4 × 10¹ ) + ( 7 × 10⁰ ) = 300 + 40 + 7
Hexadecimal Number (Base-16)
- The hexadecimal system uses 16 symbols:
0–9(same as decimal)A–F(where A=10, B=11, …, F=15)
- For Example,
1A = (1 × 16¹) + ( 10 × 16⁰) = 16 + 10 = 26 (in decimal)
| Dec | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| Hex | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
Convert Decimal to Hexadecimal
1. Using Built-in hex() Function
In this approach, we will be using the built-in function hex() that converts a decimal to a hexadecimal string.
Syntax: hex(x)
xmust be an integer (can be positive or negative).- Returns a string starting with
'0x', indicating hexadecimal. - For Example,
hex(26) = '0x1a'
Use the below logic if you want to remove the ‘0x’ prefix:
hexadecimal = hex(26)[2:] # Output: '101'
Note: [2:] slices a string from index 2 to the end, skipping the first two characters.
Code Example
decimal = 20
hex_value = hex(decimal)
print(f"Hexadecimal value: {hex_value[2:]}")Code language: Python (python)
Output:
Hexadecimal value: 14
2. Using format() Function
The format() function in Python converts an integer decimal to its hexadecimal representation as a string, without the '0x' prefix.
Syntax: format(number, 'X')
numbermust be an integer (can be positive or negative).'X': Format code for hexadecimal. ‘x’ for lowercase, ‘X’ for uppercase, ‘#X’ With0Xprefix- Returns a string of hexadecimal representation of the integer.
- For Example,
format(255, 'x') = 'ff'
Note: No '0x' like with hex().
Code Example
decimal = 13
hex_value = format(decimal, 'X') # 'x' for lowercase, 'X' for uppercase
print(f"Hexadecimal value: {hex_value}")
# Output:
# Hexadecimal value: DCode language: Python (python)
3. Using F-String Formatting
An F-string (formatted string literal) lets you embed variables, expressions, or formatting instructions directly into a string using {}.
Just prefix the string with f or F and place variables or expressions inside {}.
For Example,
name = "Alice"
age = 25
f"My name is {name} and I am {age} years old." # Output: My name is Alice and I am 25 years old.Code language: Python (python)
Numbers can be formatted like this:
f"{3.14159:.2f}" # '3.14' → 2 decimal places
f"{{5:b}}" # '101' → binary of 5
f"{255:x}" # 'ff' → hexadecimal of 255
:x inside the f-string formats the decimal as hexadecimalCode language: Python (python)
Code Example
decimal = 255
print(f"Hexadecimal value: {decimal:X}")
# Output:
# Hexadecimal value: FFCode language: Python (python)
4. Using While Loop
In this approach, we manually convert the decimal number into a hexadecimal number using while loop.
Algorithm to convert Decimal to Hexadecimal in Python:
- Initialize a string
hex_digitsthat contains all hexadecimal characters:"0123456789ABCDEF" - Create an empty string
hex_resultto store the result. - If the decimal number is 0, return
"0"directly (edge case). - While the decimal number is greater than 0:
- Divide the number by 16 and store the remainder.
- Use the remainder as an index in
hex_digitsto get the corresponding hex character. - Prepend the character to
hex_result. - Update the decimal number by dividing it by 16 (use integer division
//).
- Return the final
hex_result.
For Example: Convert Decimal 2545 to Hexadecimal:
- Step 1:
- 2545 ÷ 16 = 159 remainder 1
- Hex digit for 1 is
'1' - Add
'1'to the front →hex_result = "1" - Update decimal:
decimal = 2545 // 16 = 159
- Step 2:
- 159 ÷ 16 = 9 remainder 15
- Hex digit for 15 is
'F' - Add
'F'to the front →hex_result = "F1" - Update decimal:
decimal = 159 // 16 = 9
- Step 3:
- 9 ÷ 16 = 0 remainder 9
- Hex digit for 9 is
'9' - Add
'9'to the front →hex_result = "9F1" - Update decimal:
decimal = 9 // 16 = 0
- The loop ends when the decimal becomes 0.
- The hexadecimal representation of 2545 is:
9F1
Code Example
# function to convert decimal to hexadecimal
def decimal_to_hex(decimal):
hex_digits = "0123456789ABCDEF"
hex_result = ""
if decimal == 0:
return "0"
while decimal > 0:
remainder = decimal % 16
hex_result = hex_digits[remainder] + hex_result
decimal = decimal // 16
return hex_result
# Example
decimal = 2545
print(f"Hexadecimal value: {decimal_to_hex(decimal)}")
# Output:
# Hexadecimal value: 9F1Code language: Python (python)
5. Using Recursion
Recursion is a technique where a function calls itself to solve smaller parts of a problem until a base condition is met. It’s like solving a big problem by breaking it into smaller versions of the same problem.
In this approach, the algorithm used to convert decimals to hexadecimal is the same as explained in the above approach.
Step-by-step:
- Define a string containing all hexadecimal characters:
"0123456789ABCDEF"
This string will help map remainders (0 to 15) to their hex equivalents. - If the number (
n) is less than 16:- This is the base case of the recursion.
- Return the corresponding hex digit:
hex_digits[n]
- Else (number is 16 or more):
- Divide the number by 16 using integer division:
n // 16 - Get the remainder using:
n % 16 - Recursively call the function with
n // 16 - Append the hex digit for
n % 16to the result
- Divide the number by 16 using integer division:
- Return the final hexadecimal string by combining the recursive result and the current digit.
For Example: Convert 2545 to Hexadecimal
2545 // 16 = 159 → remainder = 1
159 // 16 = 9 → remainder =15(hex digit'F')
9 < 16 → return = 9
Now we print the remainders from last to first: 9 → F → 1 → output =9F1
Function Calls Breakdown:
decimal_to_hex_recursive(2545)2545 // 16 = 1592545 % 16 = 1→ hex digit'1'- Return:
decimal_to_hex_recursive(159) + '1'
decimal_to_hex_recursive(159)159 // 16 = 9159 % 16 = 15→ hex digit'F'- Return:
decimal_to_hex_recursive(9) + 'F'
decimal_to_hex_recursive(9)- 9 is less than 16, base case!
- Return:
'9'
Stack Unfolding (Backtracking):
Now the function starts returning values from the bottom up:
'9' + 'F'→'9F''9F' + '1'→'9F1'- Final result:
'9F1'
Code Example
# recursion function to convert hexadecimal to decimal
def decimal_to_hex_recursive(n):
hex_digits = "0123456789ABCDEF"
if n < 16:
return hex_digits[n]
return decimal_to_hex_recursive(n // 16) + hex_digits[n % 16]
decimal = 2545
print(f"Hexadecimal value: {decimal_to_hex_recursive(decimal)}")
# Output:
# Hexadecimal value: 9F1Code language: Python (python)
Convert Hexadecimal to Decimal
1. Using Built-in int() with Base 16
In this approach, we will be using the built-in function int() which converts a hexadecimal string to a decimal integer.
Syntax: int(x, base)
x: A string or number (in our case, a hexadecimal string, like"1A")base: The base of the number system (16for hexadecimal)- For Example:
int("1A", 16) # Output: 26
Code Example
hex = "1A"
decimal = int(hex, 16)
print(f"Decimal value of {hex} is {decimal}")
# Output:
# Decimal value of 1A is 26Code language: Python (python)
2. Manual Conversion Using Loop
This approach does not use the built-in function but manually converts the Hexadecimal number into a Decimal Number using a for loop in Python.
Convert Hex "1A" to Decimal:
| Dec | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| Hex | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
hex_digits = "0123456789ABCDEF"- Step 1:
Digit ='A', Value=10, Power = 0decimal += 10 × 16^0 = 10 - Step 2:
Digit ='1', Value =1, Power = 1decimal += 1 × 16^1 = 16 - Final
decimal = 10 + 16 = 26
Code Example
# function to convert hexadecimal to decimal
def hex_to_decimal(hex_str):
hex_str = hex_str.upper()
hex_digits = "0123456789ABCDEF"
decimal = 0
power = 0
for digit in reversed(hex_str):
value = hex_digits.index(digit)
decimal += value * (16 ** power)
power += 1
return decimal
# Example
print(hex_to_decimal("1A"))
# Output: 26Code language: Python (python)
Explanation
- Define a string of hexadecimal characters:
hex_digits = "0123456789ABCDEF" - Convert the input hex string to uppercase to standardize matching:
hex_str = hex_str.upper() - Reverse the string to process from least significant digit (right) to most significant digit (left):
reverse(hex_str) - Initialize:
decimal = 0→ This will store the final result.power = 0→ Represents the position (starting from the rightmost digit).
- Loop through each digit in the reversed hexadecimal string:
- Get the numeric value of the digit using its index in
hex_digits. - Multiply that value by
16^power. - Add the result to
decimal. - Increment
powerby 1 for the next digit.
- Get the numeric value of the digit using its index in
- After the loop ends, return or print the final
decimalresult.
Example walkthrough:
- Convert to uppercase:
"1A" - Reverse:
"A1" - Initialize
decimal = 0,power = 0 - Digit
'A'→ Index10and power = 0 →10 × 16^0 = 10. - Digit
'1'→ Index1and power = 1 →1 × 16^1 = 16 - Final result:
10 + 16 = 26
Summary
Python provides multiple ways to convert a decimal number to its hexadecimal equivalent, ranging from quick built-in functions to manually implemented logic for learning and customization.
- If you want a fast and simple solution, built-in methods like
hex(),int(),format(), or f-strings are the best choices. - For better control over formatting or to generate uppercase/lowercase results without prefixes,
format()and f-strings are more flexible. - If you’re learning how number systems work, the manual loop method helps you understand the conversion process step-by-step.
- The recursive method is a more mathematical and elegant approach, ideal for improving your understanding of function calls and base cases.

Leave a Reply