Convert Hex String to Bytes in Python

How can I convert a long hex string to a Python bytes object?

I have a long sequence of hex digits in a string, such as:

000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44

It’s much longer, several kilobytes. Is there a built-in way to convert this to a bytes object in Python 2.6/3?

How do I handle this using Python hex to bytes conversion?

Oh, that’s an interesting one! You can easily convert a hex string to bytes in Python using the bytes.fromhex() method, which is super convenient and straightforward. Here’s how you do it:

result = bytes.fromhex(some_hex_string)

This method is built-in, intuitive, and works well with Python hex to bytes operations. It’s available in Python 3, so if you’re using that, you’re all set!

Good suggestion above! Here’s another method that you can use—it’s almost the same in functionality but works with bytearray. If you’re comfortable using mutable byte objects or need mutability, try this:

result = bytearray.fromhex(some_hex_string)

The added advantage is that bytearray gives you a mutable sequence of bytes, which can be handy in some cases. This is also part of Python’s standard library for handling Python hex to bytes conversion.

Both of those are solid answers! Another commonly used option, especially if you’re dealing with legacy Python (like Python 2.6), is to go with the binascii module. It provides the unhexlify() function, which is very efficient for this task:

import binascii
result = binascii.unhexlify(some_hex_string)

This method works across Python 2 and Python 3, making it a versatile choice for Python hex to bytes conversion. It’s been around for ages and is a favorite for many Python developers working with binary data.