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.

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.
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:
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:
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:
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.
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:
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:
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:
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 toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.