The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Create literal bytes | payload = b'GET / HTTP/1.1\r\n' | View examples |
| Create bytes from integers | payload = bytes([0, 127, 255]) | View examples |
| Encode Unicode text | payload = text.encode('utf-8') | View examples |
| Read one byte value | value = payload[0] | View examples |
| Copy a byte range | header = payload[:4] | View examples |
| Find a byte marker | offset = payload.find(b'\r\n') | View examples |
| Create a mutable copy | buffer = bytearray(payload) | View examples |
| Replace one byte | buffer[offset] = value | View examples |
| Append binary data | buffer.extend(chunk) | View examples |
| Create a buffer view | view = memoryview(buffer) | View examples |
| Create a read-only view | readonly = view.toreadonly() | View examples |
| Release a view | view.release() | View examples |
| Cast bytes to elements | words = memoryview(buffer).cast('H') | View examples |
| Materialize view values | values = view.tolist() | View examples |
| Pack a portable header | header = struct.pack('!HI', version, length) | View examples |
| Unpack exact-size data | version, length = struct.unpack('!HI', header) | View examples |
| Unpack at an offset | values = struct.unpack_from('!HI', buffer, offset) | View examples |
| Render hexadecimal bytes | text = payload.hex(sep=' ') | View examples |
| Parse hexadecimal text | payload = bytes.fromhex(text) | View examples |
Binary protocols operate on octets, while Python text operates on Unicode code points. bytes is immutable, bytearray is mutable, and memoryview exposes another object's buffer without an immediate copy. Reliable parsers make byte order, field size, signedness, framing, and validation explicit before interpreting attacker-controlled data.
Step by step
Detailed examples
Construct bytes without confusing text and octets
A bytes literal is limited to ASCII source characters plus escapes. bytes(iterable) validates that every integer is between 0 and 255; bytes(n) creates n zero bytes rather than encoding the decimal number. Encode str explicitly at text boundaries, and never use str(binary) as a decoder because it produces a representation such as b'...'.
literal = b"ABC"
from_integers = bytes([65, 66, 67])
zeros = bytes(3)
print(literal == from_integers)
print(list(zeros)) True
[0, 0, 0]Index and slice binary sequences
Indexing bytes or bytearray returns an integer; slicing returns a binary sequence of the same core type. Search with integer values or bytes-like subsequences, and split only on delimiters guaranteed by the protocol. Methods resembling text operations are intended mainly for ASCII-compatible binary formats and do not perform Unicode-aware classification.
payload = b"PNG\r\n"
print(payload[0])
print(payload[:3])
print(payload.find(b"\r\n")) 80
b'PNG'
3Edit buffers with bytearray
bytearray supports indexed assignment, slice replacement, append, extend, and in-place operations. Resizing fails while an exported memoryview exists because that would invalidate the view. Mutating individual bytes is useful for checksums and protocol fields; validate offsets before editing and avoid sharing a mutable buffer across threads without synchronization.
buffer = bytearray(b"v0:data")
buffer[1] = ord("1")
buffer.extend(b"!")
print(bytes(buffer)) b'v1:data!'Expose and slice buffers without copying
memoryview references an exporter through the buffer protocol. Slices are views, so writes through a writable view update the original object; readonly views reject assignment. Release long-lived views promptly when the exporter must resize or close. Contiguity, dimensionality, format, and itemsize matter when interoperating with typed buffers.
buffer = bytearray(b"abcdef")
with memoryview(buffer) as view:
view[1:4] = b"XYZ"
print(view.readonly)
print(buffer.decode("ascii")) False
aXYZefCast aligned binary data to typed elements
memoryview.cast changes the element format and optionally shape without changing the underlying bytes. One side of a cast must be a byte format, and the total byte length must fit the destination item size. Native format codes use native byte order and alignment; for portable wire formats prefer struct with an explicit prefix such as !, >, or <.
view = memoryview(b"abcd").cast("B", shape=[2, 2])
print(view.tolist())
print(view.nbytes, view.itemsize) [[97, 98], [99, 100]]
4 1Pack fixed-width fields with struct
struct format prefixes define byte order, size, and alignment. Network protocols normally use ! (network big-endian) or an explicitly specified order; the default @ uses native sizes and padding and is unsuitable for portable files. Check calcsize(), bound offsets, and reject truncated buffers before unpacking.
import struct
header = struct.pack("!HI", 3, 4096)
print(header.hex())
print(struct.unpack("!HI", header))
print(struct.calcsize("!HI")) 000300001000
(3, 4096)
6Render, parse, and validate external binary input
hex() is convenient for logs and interchange, while fromhex() ignores ASCII whitespace and rejects non-hexadecimal input. Base encodings are representations, not encryption or authentication. Before allocating or slicing, validate magic bytes, declared lengths, numeric ranges, and total availability; cap decompressed or nested structures separately.
record = bytes.fromhex("CA FE 00 03 61 62 63")
if record[:2] != b"\xca\xfe":
raise ValueError("bad magic")
size = int.from_bytes(record[2:4], "big")
payload = record[4:]
if size != len(payload):
raise ValueError("bad length")
print(payload.decode("ascii")) abcLocal code tester
Decode a portable binary record
Validate a magic value and length before decoding the record payload.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
- Python Software FoundationBinary Sequence Types — bytes, bytearray, memoryviewdocs.python.org
- Python Software Foundationstruct — Interpret bytes as packed binary datadocs.python.org
- Python Software FoundationBinary Data Servicesdocs.python.org
- Python Software FoundationBuffer Protocoldocs.python.org
- Python Software Foundationcodecs — Codec registry and base classesdocs.python.org
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



