Explain Codes LogoExplain Codes Logo

How to convert hexadecimal string to bytes in Python?

python
hexadecimal-conversion
bytes-conversion
python-3
Nikita BarsukovbyNikita Barsukov·Dec 7, 2024
TLDR

Here's a "mic drop" 🎤 moment with Python's bytes.fromhex():

hex_str = "68656c6f" bytes_obj = bytes.fromhex(hex_str) print(bytes_obj) # b'hello'

No frills, just action - no '0x' or spaces allowed for a seamless transformation.

Python version-specific conversion

Python 3 did bring a lot more than just f-strings. bytes.fromhex() is your go-to for hex to bytes conversion:

hex_string = "4A6F7921" bytes_result = bytes.fromhex(hex_string)

Old-school Pythonistas, you're not left behind. For Python 2.7, here's your mantra:

hex_string = "4A6F7921" bytes_result = hex_string.decode("hex")

Dealing with extra symbols

Messy hex string with spaces or a 0x prefix? Fear not, cleaning is on the house:

dirty_hex_string = "0x4a 6f 79 21" clean_hex_string = dirty_hex_string.replace("0x", "").replace(" ", "") bytes_result = bytes.fromhex(clean_hex_string) # because clean code wins medals!

Additional conversion methods

Using binascii to Byte-tify

From hex to integers with the binascii module, because it's not all greek:

import binascii hex_string = "01FF" bytes_result = binascii.unhexlify(hex_string) # To integers int_value = int(hex_string, 16) # Trust me, it's 511.

Numeric conversions via struct.unpack

Done with ASCII? Convert bytes to actual numbers, because bytes-bite:

import struct bytes_data = b'\x00\x01' number = struct.unpack('!H', bytes_data)[0] # H is for 'Huge discovery'

Get your endian right (! for big-endian, < little-endian).

codecs provides another road to Rome

codecs library, the unsung hero in decoding hex strings to bytes:

import codecs hex_string = "deadbeef" bytes_result = codecs.decode(hex_string, "hex")

Advanced conversions and edge cases

Bytes: Go big or go home!

Large hex strings? Performance counts, so measure if you smell bottlenecks. bytes.fromhex(), you got our back!

Know your types with struct

struct.unpack does ask for attention. Decode bytes to number, but know your data type and byte length.

Modifying post-conversion: 'bytearray' is your pal

bytearray.fromhex() method, the swiss army knife for hex adjustment post-conversion:

hex_string = "48656c6c6f" byte_array = bytearray.fromhex(hex_string) # Modify the byte_array as needed, bytes can have different tastes too!