Decimal and hexadecimal are two different ways of representing numbers. Decimal uses base-10 (0-9), while hexadecimal uses base-16 (0-9 and A-F, where A=10, B=11, C=12, D=13, E=14, and F=15). Converting between these systems is a common task in programming, particularly when working with memory addresses, color codes, or data representation at a lower level. This post will show you how to easily convert decimal numbers to hexadecimal in Python.
Method 1: Using the hex()
Function
Python provides a built-in function, hex()
, that directly converts a decimal integer to its hexadecimal representation. The function returns a string starting with “0x”, indicating it’s a hexadecimal value.
= 255
decimal_number
= hex(decimal_number)
hexadecimal_number
print(f"The hexadecimal representation of {decimal_number} is: {hexadecimal_number}")
This code will output:
The hexadecimal representation of 255 is: 0xff
If you don’t want the “0x” prefix, you can easily slice it off:
= 255
decimal_number
= hex(decimal_number)[2:] #Slice from index 2 onwards
hexadecimal_number
print(f"The hexadecimal representation of {decimal_number} is: {hexadecimal_number}")
This will output:
The hexadecimal representation of 255 is: ff
Method 2: Using the format()
Function
The format()
function offers another flexible approach. It allows you to specify the base for number conversion using the 'x'
or 'X'
format specifier (lowercase ‘x’ for lowercase hexadecimal letters, uppercase ‘X’ for uppercase).
= 255
decimal_number
= format(decimal_number, 'x') #Lowercase hexadecimal
hexadecimal_number
print(f"The hexadecimal representation of {decimal_number} is: {hexadecimal_number}")
= format(decimal_number, 'X') #Uppercase hexadecimal
hexadecimal_number_uppercase
print(f"The uppercase hexadecimal representation of {decimal_number} is: {hexadecimal_number_uppercase}")
This will output:
The hexadecimal representation of 255 is: ff
The uppercase hexadecimal representation of 255 is: FF
Method 3: Manual Conversion (for educational purposes)
While the built-in functions are the most efficient, understanding the underlying process can be beneficial. Here’s a manual conversion method, illustrating the algorithm:
def decimal_to_hex(decimal_num):
= "0123456789ABCDEF"
hex_digits if decimal_num == 0:
return "0"
= ""
hex_string while decimal_num > 0:
= decimal_num % 16
remainder = hex_digits[remainder] + hex_string
hex_string //= 16
decimal_num return hex_string
= 4567
decimal_number
= decimal_to_hex(decimal_number)
hexadecimal_number
print(f"The hexadecimal representation of {decimal_number} is: {hexadecimal_number}")
This will output:
The hexadecimal representation of 4567 is: 11D7
This manual approach demonstrates the process of repeatedly dividing by 16 and collecting the remainders. However, for practical applications, the built-in hex()
and format()
functions are strongly recommended for their efficiency and readability.