PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Programs and Examples » Python Convert a Decimal Number to Hexadecimal and Vice Versa

Python Convert a Decimal Number to Hexadecimal and Vice Versa

Updated on: April 22, 2025 | Leave a Comment

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
  • Convert Decimal to Hexadecimal
    • 1. Using Built-in hex() Function
    • 2. Using format() Function
    • 3. Using F-String Formatting
    • 4. Using While Loop
    • 5. Using Recursion
  • Convert Hexadecimal to Decimal
    • 1. Using Built-in int() with Base 16
    • 2. Manual Conversion Using Loop
  • Summary

Decimal and Hexadecimal Numbers

Decimal Number (Base-10)

  • The decimal system is the standard number system we use every day.
  • It uses 10 digits: 0 to 9.
  • 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)
Dec0123456789101112131415
Hex0123456789ABCDEF

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)

  • x must 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')

  • number must be an integer (can be positive or negative).
  • 'X': Format code for hexadecimal. ‘x’ for lowercase, ‘X’ for uppercase, ‘#X’ With 0X prefix
  • 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:

  1. Initialize a string hex_digits that contains all hexadecimal characters: "0123456789ABCDEF"
  2. Create an empty string hex_result to store the result.
  3. If the decimal number is 0, return "0" directly (edge case).
  4. 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_digits to get the corresponding hex character.
    • Prepend the character to hex_result.
    • Update the decimal number by dividing it by 16 (use integer division //).
  5. 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:

  1. Define a string containing all hexadecimal characters:
    "0123456789ABCDEF"
    This string will help map remainders (0 to 15) to their hex equivalents.
  2. If the number (n) is less than 16:
    • This is the base case of the recursion.
    • Return the corresponding hex digit: hex_digits[n]
  3. 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 % 16 to the result
  4. 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:

  1. decimal_to_hex_recursive(2545)
    • 2545 // 16 = 159
    • 2545 % 16 = 1 → hex digit '1'
    • Return: decimal_to_hex_recursive(159) + '1'
  2. decimal_to_hex_recursive(159)
    • 159 // 16 = 9
    • 159 % 16 = 15 → hex digit 'F'
    • Return: decimal_to_hex_recursive(9) + 'F'
  3. 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 (16 for 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:

Dec0123456789101112131415
Hex0123456789ABCDEF
  • hex_digits = "0123456789ABCDEF"
  • Step 1:
    Digit = 'A', Value= 10, Power = 0
    decimal += 10 × 16^0 = 10
  • Step 2:
    Digit = '1', Value = 1, Power = 1
    decimal += 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

  1. Define a string of hexadecimal characters: hex_digits = "0123456789ABCDEF"
  2. Convert the input hex string to uppercase to standardize matching: hex_str = hex_str.upper()
  3. Reverse the string to process from least significant digit (right) to most significant digit (left): reverse(hex_str)
  4. Initialize:
    • decimal = 0 → This will store the final result.
    • power = 0 → Represents the position (starting from the rightmost digit).
  5. 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 power by 1 for the next digit.
  6. After the loop ends, return or print the final decimal result.

Example walkthrough:

  1. Convert to uppercase: "1A"
  2. Reverse: "A1"
  3. Initialize decimal = 0, power = 0
  4. Digit 'A' → Index 10 and power = 0 → 10 × 16^0 = 10.
  5. Digit '1' → Index 1 and power = 1 → 1 × 16^1 = 16
  6. 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.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com