memoryview.hex()
The readable form of a binary buffer. Same method as bytes.hex, and the natural partner to bytes.fromhex for round trips.
Demo
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
| Name | Type | Required | Description |
|---|---|---|---|
| sep | str | no (None) | Separator between bytes, e.g. ' ' or ':'. Must be a single character. |
| bytes_per_sep | int | no (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
text = view.hex() restored = bytes.fromhex(text)
view.hex(' ') # '61 62 63' view.hex('_', 4) # groups of four bytes
log.debug("magic=%s", view[:4].hex())
Examples
Pitfalls
int(memoryview(b'\x10').hex())
int(memoryview(b'\x10').hex(), 16)
memoryview(b'\xab').hex() == 'AB'
memoryview(b'\xab').hex().upper() == 'AB'
hex(255), memoryview(b'\xff').hex()
hex(n) for ints, view.hex() for buffers
When to use
- 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
- 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
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