How to convert a decimal number to hexadecimal in Python?

PythonPythonBeginner
Practice Now

Introduction

In this Python tutorial, we will explore the process of converting decimal numbers to their hexadecimal equivalents. By understanding the fundamentals of decimal and hexadecimal number systems, you will gain the knowledge to effectively convert between these two representations using Python.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/os_system("`Operating System and System`") python/BasicConceptsGroup -.-> python/python_shell("`Python Shell`") subgraph Lab Skills python/numeric_types -.-> lab-417960{{"`How to convert a decimal number to hexadecimal in Python?`"}} python/type_conversion -.-> lab-417960{{"`How to convert a decimal number to hexadecimal in Python?`"}} python/math_random -.-> lab-417960{{"`How to convert a decimal number to hexadecimal in Python?`"}} python/os_system -.-> lab-417960{{"`How to convert a decimal number to hexadecimal in Python?`"}} python/python_shell -.-> lab-417960{{"`How to convert a decimal number to hexadecimal in Python?`"}} end

Understanding Decimal and Hexadecimal Numbers

Decimal Number System

The decimal number system is the most commonly used number system, which uses 10 digits (0-9) to represent numbers. In the decimal system, the value of a digit depends on its position within the number. The rightmost digit represents the ones place, the next digit to the left represents the tens place, and so on, with each successive digit representing a higher power of 10.

For example, the decimal number 1234 can be broken down as:
1 (thousands) + 2 (hundreds) + 3 (tens) + 4 (ones) = 1000 + 200 + 30 + 4 = 1234

Hexadecimal Number System

The hexadecimal number system, also known as "hex," is a base-16 number system that uses 16 digits: 0-9 and A-F (where A represents 10, B represents 11, and so on). Hexadecimal numbers are commonly used in computer programming and digital electronics because they provide a compact way to represent binary data.

In the hexadecimal system, each digit represents a value from 0 to 15, with the rightmost digit representing the ones place, the next digit to the left representing the sixteens place, and so on, with each successive digit representing a higher power of 16.

For example, the hexadecimal number 0x1A3F can be broken down as:
1 (256s) + 10 (16s) + 3 (ones) + 15 (ones) = 256 + 160 + 3 + 15 = 434 (in decimal)

graph TD A[Decimal Number System] --> B[Base 10] B --> C[0-9] A --> D[Hexadecimal Number System] D --> E[Base 16] E --> F[0-9, A-F]

Converting Decimal to Hexadecimal in Python

Built-in hex() Function

Python provides a built-in function called hex() that can be used to convert a decimal number to its hexadecimal representation. The hex() function takes a single argument, which is the decimal number to be converted, and returns the corresponding hexadecimal string, starting with the prefix 0x.

Here's an example:

decimal_num = 42
hex_num = hex(decimal_num)
print(hex_num)  ## Output: '0x2a'

In this example, the decimal number 42 is converted to the hexadecimal string '0x2a'.

Manual Conversion

Alternatively, you can perform the decimal-to-hexadecimal conversion manually using Python's built-in functions and string manipulation. Here's how you can do it:

def decimal_to_hex(decimal_num):
    hex_digits = "0123456789ABCDEF"
    hex_num = ""
    
    while decimal_num > 0:
        remainder = decimal_num % 16
        hex_num = hex_digits[remainder] + hex_num
        decimal_num //= 16
    
    return "0x" + hex_num

decimal_num = 42
hex_num = decimal_to_hex(decimal_num)
print(hex_num)  ## Output: '0x2A'

In this example, the decimal_to_hex() function takes a decimal number as input and returns the corresponding hexadecimal string. The function uses a while loop to repeatedly divide the decimal number by 16 and append the appropriate hexadecimal digit to the result.

graph TD A[Decimal Number] --> B[Divide by 16] B --> C[Get Remainder] C --> D[Append Hexadecimal Digit] D --> E[Update Decimal Number] E --> B B --> F[Hexadecimal Number]

Both the built-in hex() function and the manual conversion approach can be used to convert decimal numbers to their hexadecimal representations in Python.

Applying Hexadecimal Conversion in Python

Representing Hexadecimal Values

In Python, you can represent hexadecimal values using the 0x prefix. This is a common way to denote hexadecimal numbers in programming languages.

hex_num = 0x2A
print(hex_num)  ## Output: 42

In the example above, the hexadecimal number 0x2A is assigned to the variable hex_num, which has a decimal value of 42.

Hexadecimal Color Representation

One common application of hexadecimal conversion in Python is the representation of color values. In web development and computer graphics, colors are often represented using hexadecimal codes, where each pair of hexadecimal digits represents the intensity of red, green, and blue (RGB) components.

## Represent a color in hexadecimal
color_hex = 0xFF0000
print(color_hex)  ## Output: 16711680

## Convert hexadecimal color to RGB
red = (color_hex >> 16) & 0xFF
green = (color_hex >> 8) & 0xFF
blue = color_hex & 0xFF
print(f"RGB: ({red}, {green}, {blue})")  ## Output: RGB: (255, 0, 0)

In this example, the hexadecimal color 0xFF0000 represents the color red, which has a red component of FF (255 in decimal), and green and blue components of 00 (0 in decimal). The code demonstrates how to extract the individual RGB components from the hexadecimal color value.

Hexadecimal in File Formats

Hexadecimal representation is also commonly used in file formats, such as image, audio, and video files, where it is used to store metadata, headers, and other binary data.

## Read a file in hexadecimal
with open("example.bin", "rb") as file:
    hex_data = file.read().hex()
    print(hex_data)

In this example, the contents of the example.bin file are read and converted to a hexadecimal string using the hex() function.

By understanding how to convert decimal numbers to hexadecimal and apply hexadecimal conversion in Python, you can work with a wide range of applications and file formats that use this representation.

Summary

By the end of this Python tutorial, you will have a solid understanding of how to convert decimal numbers to their hexadecimal counterparts. This skill is particularly useful in various programming and computer science applications where hexadecimal representation is commonly used. With the knowledge gained, you can confidently apply this conversion process in your Python projects.

Other Python Tutorials you may like