0
0
PythonProgramBeginner · 2 min read

Python Program to Convert Decimal to Hexadecimal

Use the built-in Python function hex() to convert a decimal number to hexadecimal, for example, hex(255) returns '0xff'.
📋

Examples

Input10
Output0xa
Input255
Output0xff
Input0
Output0x0
🧠

How to Think About It

To convert a decimal number to hexadecimal, repeatedly divide the number by 16 and record the remainders. These remainders correspond to hexadecimal digits from 0 to F. Collect the remainders in reverse order to form the hexadecimal number.
📐

Algorithm

1
Get the decimal number input.
2
If the number is zero, return '0x0'.
3
Initialize an empty string to store hexadecimal digits.
4
While the number is greater than zero, divide it by 16 and find the remainder.
5
Convert the remainder to its hexadecimal digit and add it to the front of the string.
6
Update the number by dividing it by 16 (integer division).
7
Return the string prefixed with '0x'.
💻

Code

python
def decimal_to_hexadecimal(num):
    if num == 0:
        return '0x0'
    hex_digits = '0123456789abcdef'
    hex_num = ''
    while num > 0:
        remainder = num % 16
        hex_num = hex_digits[remainder] + hex_num
        num //= 16
    return '0x' + hex_num

# Example usage
print(decimal_to_hexadecimal(255))
Output
0xff
🔍

Dry Run

Let's trace the decimal number 255 through the code.

1

Initial check

num = 255, not zero, continue

2

First iteration

remainder = 255 % 16 = 15, hex digit = 'f', hex_num = 'f', num = 255 // 16 = 15

3

Second iteration

remainder = 15 % 16 = 15, hex digit = 'f', hex_num = 'f' + 'f' = 'ff', num = 15 // 16 = 0

4

Loop ends

num is 0, stop loop

5

Return result

Return '0x' + 'ff' = '0xff'

numremainderhex_num
25515f
1515ff
💡

Why This Works

Step 1: Using modulo to find hex digits

The % operator finds the remainder when dividing by 16, which corresponds to a single hexadecimal digit.

Step 2: Building the hex string backwards

Each new digit is added to the front of the string because the first remainder is the least significant digit.

Step 3: Prefixing with '0x'

The returned string is prefixed with '0x' to indicate it is a hexadecimal number.

🔄

Alternative Approaches

Using built-in hex() function
python
num = 255
print(hex(num))
This is the simplest and fastest way but returns a string with '0x' prefix and lowercase letters.
Using format() function
python
num = 255
print(format(num, 'x'))
Returns the hexadecimal string without '0x' prefix; useful when you want just the hex digits.
Using f-string formatting
python
num = 255
print(f'{num:x}')
Similar to format(), this is concise and readable for inline conversions.

Complexity: O(log n) time, O(log n) space

Time Complexity

The loop runs proportional to the number of hexadecimal digits, which is logarithmic in base 16 of the input number.

Space Complexity

The space used is proportional to the number of digits in the hexadecimal representation, stored as a string.

Which Approach is Fastest?

Using the built-in hex() function is fastest and simplest, while manual conversion helps understand the process.

ApproachTimeSpaceBest For
Manual conversionO(log n)O(log n)Learning and custom formatting
Built-in hex()O(1)O(log n)Quick and simple conversion
format() or f-stringO(1)O(log n)Clean output without prefix
💡
Use Python's built-in hex() function for quick decimal to hexadecimal conversion.
⚠️
Beginners often forget to reverse the order of remainders, resulting in incorrect hexadecimal output.