📜  python hex to bytes string - Python (1)

📅  最后修改于: 2023-12-03 14:45:58.596000             🧑  作者: Mango

Python Hex to Bytes String

Introduction

This guide demonstrates how to convert a hex string to a bytes string in Python. The bytes string can be used to manipulate binary data efficiently. Python provides several built-in functions to perform this conversion.

Method 1: Using bytes.fromhex()

The bytes.fromhex() method is a built-in function that converts a hex string to a bytes object.

hex_string = "48656c6c6f20576f726c64"
bytes_string = bytes.fromhex(hex_string)
Method 2: Using binascii.unhexlify()

Another way to convert a hex string to a bytes string is by using the unhexlify() function from the binascii module.

import binascii

hex_string = "48656c6c6f20576f726c64"
bytes_string = binascii.unhexlify(hex_string)

Note: Both methods assume that the hex string contains an even number of hexadecimal characters.

Example

Here's a complete example that demonstrates the conversion from a hex string to a bytes string:

import binascii

hex_string = "48656c6c6f20576f726c64"
bytes_string = bytes.fromhex(hex_string)
print(f"Bytes String: {bytes_string}")

# Output: Bytes String: b'Hello World'
Conclusion

Converting a hex string to a bytes string in Python can be accomplished using the bytes.fromhex() method or the binascii.unhexlify() function. Choose the method that suits your requirements and ensure that the hex string has an even number of characters to avoid any errors during conversion.