Master Hex in Python: Conversions, Strings & Examples

目次

1. Introduction

Python is a widely used programming language known for its simple syntax and rich standard libraries. Among its features, support for hexadecimal numbers is applied in many areas such as data processing, bitwise operations, and color code manipulation. Hexadecimal is a numbering system that represents values using the digits 0–9 and the letters A–F. While decimal advances in units of 10, hexadecimal advances in units of 16, making it well suited for internal data manipulation and concise numeric representation in computers. It is especially essential for programmers when working with memory addresses and bit operations. This guide explains, in an easy-to-understand way, everything from the basic methods for handling hexadecimal numbers in Python to practical examples. We will carefully cover the fundamentals so beginners can follow along with confidence.

2. Basics of working with hexadecimal in Python

Python provides convenient features for working with hexadecimal numbers. In this section, we’ll cover in detail how to write hexadecimal literals, how to convert integers to hexadecimal, and how to convert hexadecimal strings to integers.

How to write hexadecimal literals

In Python, when treating a number as hexadecimal, you prefix the literal (the value written directly) with 0x or 0X. For example, you can write a hexadecimal number like the following.
# Hexadecimal literal
hex_number = 0x1A3F
print(hex_number)  # Output: 6719
In this example, we define the hexadecimal number 0x1A3F and print it in decimal. Python computes internally in base 10, but you can use hexadecimal literals.

How to convert integers to hexadecimal

Python provides a built-in function hex() to convert integers to hexadecimal notation. Using this function, you can easily convert integers to hexadecimal.
# Convert an integer to hexadecimal
number = 255
hex_number = hex(number)
print(hex_number)  # Output: 0xff
The hex() function returns a value of string type. This string is prefixed with 0x to indicate that it’s in hexadecimal.

How to convert a hexadecimal string to an integer

If you want to treat a hexadecimal string as an integer, use the int() function. In this case, pass the base (16) as the second argument to the int() function.
# Convert a hexadecimal string to an integer
hex_string = "1A3F"
decimal_number = int(hex_string, 16)
print(decimal_number)  # Output: 6719
Using this method, you can easily convert a hexadecimal string into an integer.

3. How to Convert Between Number Bases in Python

In Python, you can easily convert numbers between binary, octal, decimal, and hexadecimal. This section explains in detail the built-in functions bin(), oct(), hex(), and int() used for base conversion.

Basics of binary, octal, and hexadecimal

The following bases are commonly used when working with numbers.
  • Binary (binary): 0b or 0B is used to denote it.
  • Octal (octal): 0o or 0O is used to denote it.
  • Hexadecimal (hexadecimal): 0x or 0X is used to denote it.
Here’s how to use each of these literals directly in Python.
# Examples of base literals
binary_number = 0b1101  # binary
octal_number = 0o17     # octal
hex_number = 0x1A       # hexadecimal

print(binary_number)  # Output: 13
print(octal_number)   # Output: 15
print(hex_number)     # Output: 26
In Python, you can define numeric literals in different bases directly; they are automatically converted to decimal for processing.

How to convert between bases

Converting from decimal to other bases

In Python, you can use the following built-in functions to convert decimal numbers to other bases.
  • bin(): Converts a decimal number to binary.
  • oct(): Converts a decimal number to octal.
  • hex(): Converts a decimal number to hexadecimal.
Example:
# Convert from decimal to other bases
decimal_number = 42

binary_result = bin(decimal_number)
octal_result = oct(decimal_number)
hexadecimal_result = hex(decimal_number)

print(binary_result)    # Output: 0b101010
print(octal_result)     # Output: 0o52
print(hexadecimal_result)  # Output: 0x2a

Converting from other bases to decimal

Use the int() function to convert a string in any base to decimal. Provide the base (2, 8, 16, etc.) as the second argument. Example:
# Convert other bases to decimal
binary_string = "101010"
octal_string = "52"
hexadecimal_string = "2A"

decimal_from_binary = int(binary_string, 2)
decimal_from_octal = int(octal_string, 8)
decimal_from_hexadecimal = int(hexadecimal_string, 16)

print(decimal_from_binary)    # Output: 42
print(decimal_from_octal)     # Output: 42
print(decimal_from_hexadecimal)  # Output: 42
This makes it easy to convert any base representation to decimal.

Chained conversions between bases

For example, to convert from binary to hexadecimal, first convert the binary to decimal, then convert that to hexadecimal. Example:
# Convert from binary to hexadecimal
binary_string = "101010"
decimal_value = int(binary_string, 2)  # Convert binary to decimal
hexadecimal_value = hex(decimal_value)  # Convert decimal to hexadecimal

print(hexadecimal_value)  # Output: 0x2a
By combining Python’s built-in functions like this, you can easily perform chained conversions between bases.

4. Converting strings and hexadecimal in Python

In Python, converting a string to hexadecimal and back is straightforward. This section explains how to encode a string into hexadecimal and how to decode hexadecimal back to the original string.

Convert a string to hexadecimal (encoding)

To convert a string to its hexadecimal representation, first convert the string to bytes, then convert that to hexadecimal. In Python, this can be done using the encode() method and binascii.hexlify() or bytes.hex(). Example:
# Encode a string to hexadecimal
import binascii

text = "Hello, Python!"
# Convert the string to bytes
byte_data = text.encode("utf-8")
# Convert the bytes to a hexadecimal string
hex_data = binascii.hexlify(byte_data).decode("utf-8")

print(hex_data)  # Output: 48656c6c6f2c20507974686f6e21
There is also a simple method using bytes.hex():
# Encode a string to hexadecimal (simple version)
text = "Hello, Python!"
hex_data = text.encode("utf-8").hex()

print(hex_data)  # Output: 48656c6c6f2c20507974686f6e21
In this example, the string "Hello, Python!" is converted to bytes and then to a hexadecimal-formatted string.

Convert hexadecimal back to a string (decoding)

To restore a hexadecimal string back to the original string, first decode the hexadecimal into bytes, then decode those bytes into a string. Example:
# Decode hexadecimal back to the original string
import binascii

hex_data = "48656c6c6f2c20507974686f6e21"
# Convert hexadecimal to bytes
byte_data = binascii.unhexlify(hex_data)
# Convert the bytes to a string
text = byte_data.decode("utf-8")

print(text)  # Output: Hello, Python!
Also, there’s a simple method using bytes.fromhex():
# Decode hexadecimal back to the original string (simple version)
hex_data = "48656c6c6f2c20507974686f6e21"
text = bytes.fromhex(hex_data).decode("utf-8")

print(text)  # Output: Hello, Python!
Using this method, you can easily restore the original string from hexadecimal.

Use case: Converting file data to hexadecimal

This technique is effective not only for strings but also when handling binary files (such as images or audio data) as hexadecimal.
# Convert a file to hexadecimal
with open("example.txt", "rb") as file:
    binary_data = file.read()
    hex_data = binary_data.hex()

print(hex_data)  # Print the file contents in hexadecimal

5. Bitwise Operations with Hexadecimal in Python

Hexadecimal is very useful when performing bitwise operations. Bitwise operations are techniques for manipulating the individual bits of numbers, and they are used in efficient data processing, hardware control, encryption algorithms, and more. This section explains the basic methods and examples of performing bitwise operations on hexadecimal values in Python.

Basics of bitwise operations and operators used in Python

Bitwise operations include the following basic operations, and Python provides corresponding operators. | Bitwise operation | Operator | Description | ||–|–| | AND operation | & | Returns 1 when both bits are 1 | | OR operation | | | Returns 1 when either bit is 1 | | XOR operation | ^ | Returns 1 when the bits differ | | NOT operation | ~ | Inverts the bits | | Left shift | << | Shifts bits to the left by the specified number of positions| | Right shift | >> | Shifts bits to the right by the specified number of positions|

Examples of bitwise operations using hexadecimal

Below are concrete examples of bitwise operations using hexadecimal.

AND operation

# Hexadecimal AND operation
a = 0xF0  # 240 in hexadecimal
b = 0x0F  # 15 in hexadecimal

result = a & b
print(hex(result))  # Output: 0x0
Since a bit is 1 only when both bits are 1, the result is 0x0.

OR operation

# Hexadecimal OR operation
a = 0xF0
b = 0x0F

result = a | b
print(hex(result))  # Output: 0xff
Since a bit is 1 if either bit is 1, the result is 0xFF.

XOR operation

# Hexadecimal XOR operation
a = 0xF0
b = 0x0F

result = a ^ b
print(hex(result))  # Output: 0xff
Because a bit is 1 when the bits differ, the result is 0xFF.

NOT operation

# Hexadecimal NOT operation
a = 0xF0

result = ~a
print(hex(result))  # Output: -0xf1
The result is the value with all bits inverted. Note that Python may produce a negative value.

Shift operations

# Left shift
a = 0x01  # 1 in hexadecimal
result = a << 4
print(hex(result))  # Output: 0x10

# Right shift
a = 0x10  # 16 in hexadecimal
result = a >> 4
print(hex(result))  # Output: 0x1
Left shift moves bits to the left by the specified amount, and right shift moves them to the right. This causes a value to increase or decrease by powers of two.

Use case: Flag manipulation

Bitwise operations on hexadecimal values are also useful for manipulating flags (settings or states). Below is an example of flag manipulation.
# Example of flag manipulation
FLAG_READ = 0x01  # Read permission
FLAG_WRITE = 0x02  # Write permission
FLAG_EXECUTE = 0x04  # Execute permission

# Enable read and write
permissions = FLAG_READ | FLAG_WRITE
print(hex(permissions))  # Output: 0x3

# Remove write permission
permissions = permissions & ~FLAG_WRITE
print(hex(permissions))  # Output: 0x1

# Check execute permission
has_execute = permissions & FLAG_EXECUTE
print(bool(has_execute))  # Output: False
In this example, bitwise operations are used to manage flags efficiently.

6. Practical Examples Using Hexadecimal

Hexadecimal numbers are practically used across many areas of programming. In this section, we’ll cover representative applications of hexadecimal: color code representation, memory address manipulation, and working with binary data.

Color Code Representation and Manipulation

Hexadecimal is widely used to represent color codes in HTML and CSS. Color codes represent each RGB (red, green, blue) component as a two-digit hexadecimal value.

Basic example: Generating a color code

# Generate a hexadecimal color code from RGB values
def rgb_to_hex(red, green, blue):
    return f"#{red:02x}{green:02x}{blue:02x}"

color = rgb_to_hex(255, 165, 0)  # Orange
print(color)  # Output: #ffa500
In this example, red, green, and blue values are used as input to generate a hexadecimal color code.

Practical example: Converting a hexadecimal color code to RGB

# Extract RGB values from a hexadecimal color code
def hex_to_rgb(hex_color):
    hex_color = hex_color.lstrip("#")
    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))

rgb = hex_to_rgb("#ffa500")
print(rgb)  # Output: (255, 165, 0)
As shown, converting a hexadecimal color code to RGB format is also straightforward.

Memory Address Representation

Hexadecimal is essential for representing addresses in computer memory. In Python, you can get an object’s memory address and display it in hexadecimal.
# Display the object's memory address
variable = 42
address = hex(id(variable))

print(address)  # Output: 0x7ffee4d9c710 (example)
In this example, the id() function is used to obtain a variable’s memory address and represent it in hexadecimal. Working with memory addresses can be helpful for debugging and low-level programming.

Working with Binary Data

Hexadecimal is also very convenient for visually handling binary data. Python provides tools to display and manipulate binary data directly in hexadecimal.

Displaying a File in Hexadecimal

# Display the file contents in hexadecimal
def read_file_as_hex(file_path):
    with open(file_path, "rb") as file:
        data = file.read()
        return data.hex()

hex_data = read_file_as_hex("example.bin")
print(hex_data)  # Output the binary file contents in hexadecimal
This code reads a binary file and displays its contents as a hexadecimal string.

Manipulating Binary Data

Below is an example of manipulating binary data to change a specific pattern.
# Modify a specific part of the binary data
import binascii

original_data = b" ÿ¥ "
modified_data = original_data[:1] + b"" + original_data[2:]

print(binascii.hexlify(modified_data))  # Output: 00ff0100
Using this method, you can easily modify specific parts of binary data.

7. Summary

This article provided a comprehensive guide to working with hexadecimal numbers in Python, covering basic operations through practical examples. Here we review the key points of each section and add notes on things to watch for when handling hex numbers.

Article Recap

  1. Introduction
  • Hexadecimal numbers play an important role in programming and data processing.
  • Python provides simple yet powerful tools for working with hexadecimal numbers.
  1. Basics of Working with Hexadecimal in Python
  • Hexadecimal literals are written using 0x.
  • You can convert an integer to hexadecimal with the hex() function, and convert a hex string back to an integer with the int() function.
  1. Converting Between Bases in Python
  • Conversions between bases can be easily done using the bin(), oct(), hex(), and int() functions.
  • Through concrete examples, we learned how to convert between binary, octal, decimal, and hexadecimal.
  1. Converting Between Strings and Hex in Python
  • When converting a string to hex, combine encode() and hex().
  • To convert hex back to a string, use bytes.fromhex() or binascii.unhexlify().
  1. Bitwise Operations with Hex in Python
  • We explained how to perform basic bitwise operations such as AND, OR, XOR, NOT, and shifts using hexadecimal.
  • We showed practical examples, such as flag manipulation, in real programs.
  1. Practical Examples Using Hexadecimal
  • We introduced practical examples like generating and converting color codes, displaying memory addresses, and manipulating binary data.
  • These examples are commonly used in everyday programming tasks.

Notes When Working with Hexadecimal

  1. Data Type Considerations
  • Because hex values are often treated as strings, you should convert them to integers when performing calculations or comparisons.
  1. Uppercase and Lowercase Differences
  • Python does not distinguish between uppercase (A-F) and lowercase (a-f) hex strings. However, it’s important to standardize the format when interacting with external systems.
  1. Error Handling
  • When converting a string to hex, invalid strings (e.g., "G123") will cause an error. It’s important to validate input data beforehand.
  1. Efficiency
  • If you frequently perform bitwise or binary operations, consider data size and computational efficiency. For large datasets, choose appropriate algorithms.

Closing Remarks

Being able to work with hexadecimal numbers is highly useful for programmers. By covering hex from basic to advanced topics in this article, you can broaden your approach to data processing and algorithm design. When handling hex, select the appropriate tools and methods for your goals and use them efficiently. This concludes the guide to working with hex in Python—may it be useful for your next project or learning endeavor!

FAQ: Frequently Asked Questions About Working with Hex in Python

Q1: How do I convert an integer to hexadecimal in Python?

In Python, you can convert an integer to hexadecimal using the built-in function hex().
number = 255
hex_number = hex(number)
print(hex_number)  # Output: 0xff
The hex() function returns a string with 0x added to the result. If you want to remove 0x, you can use slicing.
clean_hex = hex(number)[2:]
print(clean_hex)  # Output: ff

Q2: How do I convert a hexadecimal string to an integer in Python?

To convert a hexadecimal string to an integer, use the int() function. By specifying the base as the second argument, you can convert numbers from any base to decimal.
hex_string = "ff"
decimal_number = int(hex_string, 16)
print(decimal_number)  # Output: 255

Q3: Is there a difference when handling uppercase and lowercase hexadecimal strings in Python?

Python does not distinguish between uppercase (e.g., A-F) and lowercase (e.g., a-f) hexadecimal strings. They are treated as the same value.
hex_upper = "FF"
hex_lower = "ff"

print(int(hex_upper, 16))  # Output: 255
print(int(hex_lower, 16))  # Output: 255
To normalize case, use the string upper() or lower() method.

Q4: How do I create a bytes object (bytes) from hexadecimal?

To convert a hexadecimal string to bytes, use bytes.fromhex().
hex_string = "48656c6c6f"  # Hexadecimal representation of "Hello"
byte_data = bytes.fromhex(hex_string)
print(byte_data)  # Output: b'Hello'
Conversely, to convert bytes to a hexadecimal string, use the hex() method.
print(byte_data.hex())  # Output: 48656c6c6f

Q5: How do I output hexadecimal in Python without the 0x prefix?

When using the hex() function, the output is prefixed with 0x. A common way to remove this 0x is to use slicing.
number = 255
hex_number = hex(number)[2:]
print(hex_number)  # Output: ff
You can also use format strings.
number = 255
formatted_hex = f"{number:x}"  # lowercase
formatted_hex_upper = f"{number:X}"  # uppercase
print(formatted_hex)  # Output: ff
print(formatted_hex_upper)  # Output: FF

Q6: How do you perform calculations with hexadecimal in Python?

You can perform calculations directly with hex values, but computations are done as integers. To display the result in hexadecimal, use the hex() function.
a = 0xA  # 10 in hexadecimal
b = 0x5  # 5 in hexadecimal

result = a + b
print(hex(result))  # Output: 0xf

Q7: Will handling an invalid hexadecimal string in Python raise an error?

Yes — attempting to process an invalid hexadecimal string will raise ValueError.
hex_string = "G123"  # Invalid hexadecimal
try:
    decimal_number = int(hex_string, 16)
except ValueError as e:
    print(f"Error: {e}")  # Output: Error: invalid literal for int() with base 16: 'G123'
To avoid errors, it is recommended to validate input beforehand or use exception handling.

Q8: How do I generate hexadecimal color codes in Python?

To generate a hexadecimal color code from RGB values, use format strings.
def rgb_to_hex(r, g, b):
    return f"#{r:02x}{g:02x}{b:02x}"

color = rgb_to_hex(255, 165, 0)  # orange
print(color)  # Output: #ffa500

Q9: How do I convert binary data to hexadecimal in Python?

To convert file data or byte sequences to a hexadecimal string, use hex().
with open("example.bin", "rb") as file:
    binary_data = file.read()
    hex_data = binary_data.hex()

print(hex_data)  # Output: Displays file contents in hexadecimal

Q10: How do I convert between hexadecimal and other bases (binary, octal, decimal) in Python?

In Python, you can easily convert using built-in functions.
# Decimal to hexadecimal
hex_value = hex(255)  # Output: 0xff

# Binary to hexadecimal
binary_value = "11111111"
hex_value = hex(int(binary_value, 2))  # Output: 0xff

# Octal to hexadecimal
octal_value = "377"
hex_value = hex(int(octal_value, 8))  # Output: 0xff
年収訴求