Skip to content
Go back

Convert Decimal to Hexadecimal in Python: A Step-by-Step Guide

Published:  at  07:32 PM

Tired of the decimal system monopolizing your attention? It’s time for a hexadecimal escape! 🚀

🔮 Problem Statement

We face the challenge of transforming an integer, comfortably housed in the decimal system we all know, to its equivalent in the hexadecimal system. The latter, base 16, is a common feature in the world of computing, especially when it comes to representing colors, memory addresses, or binary data more compactly.

The task is summarized in the following function:

def to_hex(num):
	"level: difficult; points: 7"
	dec_hex = {n + 10: chr(97 + n) for n in range(6)}
	hex = []
	while num > 0:
		hex.append(num % 16)
		num //= 16
	hex = reversed(hex)
	hex = [h if h not in dec_hex else dec_hex[h] for h in hex]
	return ''.join(map(str, hex))

Parameters:

Return Value:

Examples:

>>> to_hex(255)
'ff'
>>> to_hex(500)
'1f4'

🧩 Step-by-Step Solution

The key to this transformation lies in breaking down the original decimal number into powers of 16. To do this, we iteratively obtain the remainder and quotient of the division by 16. The remainder represents a hexadecimal digit.

dec_hex = {n + 10: chr(97 + n) for n in range(6)}

Here we create a dictionary, dec_hex, that acts as a translator between decimal values from 10 to 15 and their corresponding hexadecimal representations (‘a’ to ‘f’). A dictionary comprehension is used to generate this mapping concisely, taking advantage of the chr() function to convert ASCII codes to characters.

hex = []

We initialize an empty list called hex. This list will store the hexadecimal digits, but in reverse order to what we need.

while num > 0:
    hex.append(num % 16)
    num //= 16

This while loop is the heart of the conversion. In each iteration, we calculate the remainder (num % 16), which represents the least significant hexadecimal digit. This digit is added to the hex list. Then, we update the value of num by dividing it by 16 using integer division (num //= 16), preparing the next iteration to extract the next hexadecimal digit.

hex = reversed(hex)
hex = [h if h not in dec_hex else dec_hex[h] for h in hex]

First, we reverse the list of remainders to have the correct order of hexadecimal digits. Then, using a list comprehension, we convert the decimal digits (10 to 15) to their hexadecimal representations (a-f) by consulting the dec_hex dictionary. If a digit is not in the dictionary, it means it is less than 10 and is left as is.

return ''.join(map(str, hex))

Finally, we convert each element of the hex list to a string using map(str, hex) and join all the elements into a single string, which is the final hexadecimal representation of the original number.

Complete Solution:

def to_hex(num):
	"level: difficult; points: 7"
	dec_hex = {n + 10: chr(97 + n) for n in range(6)}
	hex = []
	while num > 0:
		hex.append(num % 16)
		num //= 16
	hex = reversed(hex)
	hex = [h if h not in dec_hex else dec_hex[h] for h in hex]
	return ''.join(map(str, hex))

🧠 Key Concepts

The concept of list comprehension and dictionary comprehension are central. They allow you to create collections of data (lists and dictionaries, respectively) concisely and readably, avoiding explicit for loops. In this case, the dictionary comprehension is used to create the mapping between decimal and hexadecimal values efficiently, and the list comprehension to transform the hexadecimal numeric digits to characters when necessary.

Integer division (//) and the modulo operator (%) are fundamental arithmetic operations for performing base conversion. Integer division returns the quotient of the division, discarding the decimal part, while the modulo operator returns the remainder. The remainder gives us the value of the digit in the new base, and the quotient is used to continue the division until the original number is reduced to zero.

The use of the reversed() function returns a reverse iterator over the original collection, allowing you to process the list in the correct order to build the final result. The use of map applies a function to each element of a collection (in this case, converting each number to a string) and the join function allows you to build a string from a list of strings.

Did you know…? Although the hexadecimal system is widely used to represent binary data compactly, some ancient cultures used numerical systems in base 60! This sexagesimal system is still used today to measure time (seconds, minutes) and angles (degrees). 🤯

💫 Final Thoughts

Converting between numerical systems is a fundamental skill in computer science. While the solution presented is functional and concise, there are alternatives, such as using Python’s native hex() function, which could further simplify the code. However, understanding the underlying mechanisms of the conversion allows us to appreciate the elegance of numerical systems and their importance in data representation.

Also, the code is susceptible to improvements in readability. Although list comprehensions are powerful, sometimes an explicit for loop could increase clarity. The choice between conciseness and readability is a balance that every developer must consider.

If you enjoyed this analysis and want to delve deeper into the world of algorithms and data structures, feel free to explore other articles on our blog! Knowledge is power, and code is the language of innovation! 😉



Previous Post
Tree Growth: Cycles, Height and Calculation with Python
Next Post
Counting CamelCase Words: A Step-by-Step Python Function