How to display a byte array as hex values
Categories:
How to Display a Byte Array as Hex Values in Python

Learn various Python methods to convert byte arrays into human-readable hexadecimal string representations, essential for debugging and data inspection.
When working with binary data in Python, such as network packets, file contents, or cryptographic outputs, you often encounter byte arrays. While these are efficient for machine processing, they are not easily readable by humans. Converting a byte array to its hexadecimal string representation is a common task for debugging, logging, or displaying data in a more understandable format. This article explores several Pythonic ways to achieve this, from built-in functions to more manual approaches, highlighting their use cases and performance characteristics.
Understanding Byte Arrays and Hexadecimal Representation
A byte array in Python is a sequence of bytes, where each byte is an integer in the range 0 to 255. Hexadecimal (base-16) is a number system that uses 16 distinct symbols, typically 0-9 and A-F. Each hexadecimal digit represents four binary digits (bits), making it a compact and convenient way to represent binary data. Two hexadecimal digits can represent a single byte (8 bits), ranging from 00
to FF
.
flowchart TD A[Byte Array Input] --> B{Iterate through bytes} B --> C[Convert each byte to hex] C --> D[Pad with leading zero if needed] D --> E[Concatenate hex strings] E --> F[Hex String Output]
Conceptual flow for converting a byte array to a hexadecimal string
Method 1: Using bytes.hex()
(Python 3.5+)
The bytes.hex()
method is the most straightforward and recommended way to convert a bytes
object to a hexadecimal string in Python 3.5 and later. It returns a string containing two hexadecimal digits for each byte in the sequence. This method is efficient and handles padding with leading zeros automatically.
data = b'\xDE\xAD\xBE\xEF'
hex_string = data.hex()
print(hex_string)
# Example with a string encoded to bytes
message = "Hello, World!"
encoded_message = message.encode('utf-8')
hex_message = encoded_message.hex()
print(hex_message)
Using the bytes.hex()
method for conversion
bytes.hex()
method is generally the most performant and Pythonic solution for modern Python versions (3.5+). Always prefer it when available.Method 2: Using binascii.hexlify()
The binascii
module provides functions to convert between binary and ASCII representations. binascii.hexlify()
is a robust function that takes a bytes
or bytearray
object and returns a bytes
object containing the hexadecimal representation. You'll typically need to decode this bytes
object to a string for display.
import binascii
data = b'\x01\x02\x03\x0A\x0B\x0C'
hex_bytes = binascii.hexlify(data)
hex_string = hex_bytes.decode('ascii')
print(hex_string)
# Or in one line:
hex_string_oneline = binascii.hexlify(data).decode('ascii')
print(hex_string_oneline)
Converting with binascii.hexlify()
Method 3: Using String Formatting with a Loop
For older Python versions or when you need more granular control over the output format (e.g., adding spaces between bytes), you can iterate through the byte array and format each byte individually. This method uses string formatting ({:02x}
) to ensure each byte is represented by two hexadecimal digits, padding with a leading zero if necessary.
data = bytearray([0x12, 0x34, 0xAB, 0xCD, 0x05, 0xF0])
hex_parts = []
for byte in data:
hex_parts.append(f"{byte:02x}")
hex_string = " ".join(hex_parts) # Join with spaces for readability
print(hex_string)
# Without spaces:
hex_string_no_spaces = "".join(f"{byte:02x}" for byte in data)
print(hex_string_no_spaces)
Manual conversion using a loop and string formatting
{:02x}
format specifier means: 0
for zero-padding, 2
for a minimum width of two characters, and x
for lowercase hexadecimal representation. Use X
for uppercase hexadecimal.Method 4: Using codecs.encode()
The codecs
module provides access to various encoders and decoders. You can use codecs.encode()
with the 'hex'
encoding to achieve the same result as binascii.hexlify()
. Similar to binascii.hexlify()
, it returns a bytes
object that needs to be decoded to a string.
import codecs
data = b'\x1A\x2B\x3C\x4D'
hex_bytes = codecs.encode(data, 'hex')
hex_string = hex_bytes.decode('ascii')
print(hex_string)
Using codecs.encode()
for hex conversion
codecs.encode()
works, bytes.hex()
or binascii.hexlify()
are generally preferred for this specific task as they are more direct and often slightly more performant.