Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Converting Between Bytes and Hex in Python

Learn to convert bytes to hex strings and back in Python with bytes.hex(), bytes.fromhex(), and binascii, including code examples and memory considerations.

~3 min readPython
#bytes#hex#binascii#encoding
Diagram showing a byte sequence on the left converting to a hexadecimal string on the right, with arrows indicating the conversion process.

When you need to work with binary data in Python, converting between bytes and a hexadecimal string is a common operation. The bytes type has built-in methods for both directions: data.hex() converts bytes to a lowercase hex string, and bytes.fromhex(hex_str) converts a hex string back to bytes. The binascii module offers equivalent functions. This article explains how these conversions work, where binascii can be useful, and what to watch out for.

Converting Bytes to Hex with bytes.hex()

The simplest way to get a hexadecimal representation of a bytes object is to call .hex(). It returns a lowercase str with two hex digits for each byte.

python
data = b'\x01\x02\xff' hex_str = data.hex() print(hex_str) # '0102ff'

The .hex() method is available on all bytes objects in Python 3.5 and later. It does not require importing a module.

If you need uppercase letters, call .upper() on the resulting string:

python
hex_str_upper = data.hex().upper() print(hex_str_upper) # '0102FF'

Converting Hex Strings to Bytes with bytes.fromhex()

The inverse operation is the class method bytes.fromhex(). It parses a string of hex digits and returns a bytes object:

python
hex_str = '0102ff' data = bytes.fromhex(hex_str) print(data) # b'\x01\x02\xff'

bytes.fromhex() ignores ASCII whitespace between hex digits, so formatted input with spaces or newlines works:

python
data = bytes.fromhex('01 02 ff') print(data) # b'\x01\x02\xff'

If the input string contains an odd number of hex digits or a character that is not a valid hex digit, the method raises ValueError.

Using binascii.hexlify() and binascii.unhexlify()

The binascii module provides hexlify() and unhexlify() for the same conversions. These are useful when you are already performing other binascii operations or when you need the hex output as bytes rather than as text.

python
import binascii data = b'\x01\x02\xff' hex_bytes = binascii.hexlify(data) print(hex_bytes) # b'0102ff' hex_str = hex_bytes.decode('ascii') print(hex_str) # '0102ff'

binascii.unhexlify() is the inverse:

python
hex_str = '0102ff' data = binascii.unhexlify(hex_str) print(data) # b'\x01\x02\xff'

Unlike bytes.fromhex(), binascii.unhexlify() does not ignore whitespace, so a string like '01 02 ff' will fail unless you remove the spaces first.

Handling Large Byte Sequences

Both bytes.hex() and binascii.hexlify() create a complete representation of the input. A hex string is roughly twice as large as the original byte sequence, so converting an entire very large object at once can use a lot of memory. If you only need to stream converted data, process the input in chunks:

python
def file_to_hex(file_path, chunk_size=8192): with open(file_path, 'rb') as f: while True: chunk = f.read(chunk_size) if not chunk: break yield chunk.hex()

This generator yields a hex string for each chunk. Consume it directly instead of collecting all chunks in a list if you want to avoid holding the full hex output in memory.

Common Pitfalls

Do not confuse bytes.hex() with the built-in hex() function. hex() converts an integer to a 0x-prefixed string; calling it on a bytes object raises TypeError.

A related issue is a 0x prefix. bytes.fromhex() expects plain hex digits, so strip the prefix first:

python
hex_str = '0x1a' data = bytes.fromhex(hex_str[2:])

Also remember that binascii.unhexlify() requires an even number of hex digits and does not ignore whitespace.

Choosing Between bytes Methods and binascii

For most modern Python code, bytes.hex() and bytes.fromhex() are the clearest choice because they are built into the type and do not require an import. binascii is useful when you are already using other functions in the module or when you want hexlify() to return bytes for direct use in binary protocols.

The performance difference between these options is not usually important for everyday code. The more important differences are the return type, whitespace handling, and compatibility: bytes.hex() was added in Python 3.5, while binascii.hexlify() is available in older Python versions.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.