memoryview.hex()

The readable form of a binary buffer. Same method as bytes.hex, and the natural partner to bytes.fromhex for round trips.

Memoryview methodPython 3.5+Live demo
Common call
view.hex()
Returns
str like '616263' — lowercase, unseparated
Replaces
''.join(f'{b:02x}' for b in view)
Watch out
no 0x prefix, so it is not a Python integer literal
memoryview.hex([sep[, bytes_per_sep]])
→ str

Demo

Live evaluation
Try:
Inputs
sstrtext to view as bytes
Output
memoryview(bytes('abc', 'utf-8')).hex()
'616263'

Each byte becomes exactly two lowercase hex digits, run together with nothing between them. "abc" gives 616263, because a is 0x61. The output has no 0x prefix and no separators, so its length is always exactly twice the number of bytes — which makes it easy to slice back apart. The non-ascii case again shows UTF-8 at work: one accented character contributes four hex digits, because it is two bytes.

Parameters

NameTypeRequiredDescription
sepstrno (None)Separator between bytes, e.g. ' ' or ':'. Must be a single character.
bytes_per_sepintno (1)How many bytes go between separators. Negative counts from the left instead of the right.

Return value

str — A string of two lowercase hex digits per byte, with no 0x prefix and no separator unless one is requested.

Common patterns

Round-trip binary through text
bytes.fromhex reverses it exactly, which makes hex a safe transport for binary.
text = view.hex()
restored = bytes.fromhex(text)
Readable separators for a dump
A separator every byte or every four makes long dumps scannable.
view.hex(' ')       # '61 62 63'
view.hex('_', 4)   # groups of four bytes
Log a buffer prefix
The first few bytes usually identify a format.
log.debug("magic=%s", view[:4].hex())

Examples

1. ASCII
memoryview(b'abc').hex()
Returns
'616263'
2. With spaces
memoryview(b'abc').hex(' ')
Returns
'61 62 63'
3. Empty
memoryview(b'').hex()
Returns
''
4. Round trip
bytes.fromhex(memoryview(b'abc').hex())
Returns
b'abc'
5. Non-ascii
memoryview('é'.encode()).hex()
Returns
'c3a9'
6. Not an int literal
int(memoryview(b'abc').hex(), 16)
Returns
6382179 # base must be given

Pitfalls

1. No 0x prefix
Unlike the built-in hex(), the output is bare digits. Passing it to int() without a base makes Python read it as decimal, which either fails or silently gives a wrong number.
Read as decimal
int(memoryview(b'\x10').hex())
10 # should be 16
State the base
int(memoryview(b'\x10').hex(), 16)
16
2. Always lowercase
There is no option for uppercase. Comparing against an uppercase fixture fails on case alone, which is an easy hour to lose in a test.
Case mismatch
memoryview(b'\xab').hex() == 'AB'
False
Normalise
memoryview(b'\xab').hex().upper() == 'AB'
True
3. It is not the built-in hex()
hex() takes one integer and returns something like 0xff. This method takes a whole buffer and returns two digits per byte. The names match but the outputs are not comparable.
Different things
hex(255), memoryview(b'\xff').hex()
('0xff', 'ff')
Pick deliberately
hex(n) for ints, view.hex() for buffers
clear intent

When to use

Use it
  • Logging or displaying a binary buffer readably
  • Round-tripping binary data through a text channel
  • Test fixtures where a bytes literal would be unreadable
  • Checking magic numbers at the head of a file
Reach for something else
  • You need a Python int literal → the built-in hex()
  • The data is text → decode it instead
  • Compact transport matters → base64 is a third shorter

Notes

Complexity
O(n) — two characters emitted per byte
Return
A new str, exactly twice the byte length when no separator is used
CPython impl
Objects/memoryobject.c :: memory_hex
Memory
Allocates a string twice the size of the buffer
Thread-safe
A concurrently mutated source gives an inconsistent snapshot

FAQ

bytes.fromhex reverses it exactly. The round trip is lossless, which is what makes hex a dependable way to carry binary through a text-only channel.

bytes.fromhex(view.hex()) == view.tobytes()
# True

History

3.5
hex() added to bytes, bytearray and memoryview.
3.8
The sep and bytes_per_sep arguments added.