Python Program to Convert Decimal to Hexadecimal
hex() to convert a decimal number to hexadecimal, for example, hex(255) returns '0xff'.Examples
How to Think About It
Algorithm
Code
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))
Dry Run
Let's trace the decimal number 255 through the code.
Initial check
num = 255, not zero, continue
First iteration
remainder = 255 % 16 = 15, hex digit = 'f', hex_num = 'f', num = 255 // 16 = 15
Second iteration
remainder = 15 % 16 = 15, hex digit = 'f', hex_num = 'f' + 'f' = 'ff', num = 15 // 16 = 0
Loop ends
num is 0, stop loop
Return result
Return '0x' + 'ff' = '0xff'
| num | remainder | hex_num |
|---|---|---|
| 255 | 15 | f |
| 15 | 15 | ff |
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
num = 255 print(hex(num))
num = 255 print(format(num, 'x'))
num = 255 print(f'{num:x}')
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual conversion | O(log n) | O(log n) | Learning and custom formatting |
| Built-in hex() | O(1) | O(log n) | Quick and simple conversion |
| format() or f-string | O(1) | O(log n) | Clean output without prefix |
hex() function for quick decimal to hexadecimal conversion.