The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Create literal bytespayload = b'GET / HTTP/1.1\r\n'View examples
Create bytes from integerspayload = bytes([0, 127, 255])View examples
Encode Unicode textpayload = text.encode('utf-8')View examples
Read one byte valuevalue = payload[0]View examples
Copy a byte rangeheader = payload[:4]View examples
Find a byte markeroffset = payload.find(b'\r\n')View examples
Create a mutable copybuffer = bytearray(payload)View examples
Replace one bytebuffer[offset] = valueView examples
Append binary databuffer.extend(chunk)View examples
Create a buffer viewview = memoryview(buffer)View examples
Create a read-only viewreadonly = view.toreadonly()View examples
Release a viewview.release()View examples
Cast bytes to elementswords = memoryview(buffer).cast('H')View examples
Materialize view valuesvalues = view.tolist()View examples
Pack a portable headerheader = struct.pack('!HI', version, length)View examples
Unpack exact-size dataversion, length = struct.unpack('!HI', header)View examples
Unpack at an offsetvalues = struct.unpack_from('!HI', buffer, offset)View examples
Render hexadecimal bytestext = payload.hex(sep=' ')View examples
Parse hexadecimal textpayload = 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

01

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'...'.

Compare bytes construction forms
literal = b"ABC"
from_integers = bytes([65, 66, 67])
zeros = bytes(3)
print(literal == from_integers)
print(list(zeros))
Output
True
[0, 0, 0]
Back to quick reference ↑
03

Edit 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.

Patch a binary header
buffer = bytearray(b"v0:data")
buffer[1] = ord("1")
buffer.extend(b"!")
print(bytes(buffer))
Output
b'v1:data!'
Back to quick reference ↑
04

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.

Modify a slice through a view
buffer = bytearray(b"abcdef")
with memoryview(buffer) as view:
    view[1:4] = b"XYZ"
    print(view.readonly)
print(buffer.decode("ascii"))
Output
False
aXYZef
Back to quick reference ↑
05

Cast 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 <.

Cast four bytes into a shaped byte view
view = memoryview(b"abcd").cast("B", shape=[2, 2])
print(view.tolist())
print(view.nbytes, view.itemsize)
Output
[[97, 98], [99, 100]]
4 1
Back to quick reference ↑
06

Pack 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.

Round-trip a network-order header
import struct

header = struct.pack("!HI", 3, 4096)
print(header.hex())
print(struct.unpack("!HI", header))
print(struct.calcsize("!HI"))
Output
000300001000
(3, 4096)
6
Back to quick reference ↑
07

Render, 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.

Parse and validate a compact record
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"))
Output
abc
Back to quick reference ↑

Local code tester

Decode a portable binary record

Validate a magic value and length before decoding the record payload.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software FoundationBinary Sequence Types — bytes, bytearray, memoryviewdocs.python.org
  2. Python Software Foundationstruct — Interpret bytes as packed binary datadocs.python.org
  3. Python Software FoundationBinary Data Servicesdocs.python.org
  4. Python Software FoundationBuffer Protocoldocs.python.org
  5. 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.

Share feedback