Python Binary
Sequence Types:
Bytes
Understanding bytes, bytearray, and Memory Mapping
Subject: Python Programming
What are Bytes?
► Bytes are sequences of 8-bit integers (values ranging
from 0 to 255).
► They represent raw binary data, essential for processing
non-text files.
► Property: The 'bytes' object is IMMUTABLE.
► Syntax: Defined using the prefix 'b' before a string.
► Example: b_data = b'Hello'
Why do we need Bytes?
► Images & Audio: Storing and processing media files.
► Network Communication: Data sent over the internet is
usually in byte format.
► File Handling: Reading 'rb' (read binary) or writing 'wb'
(write binary).
► Encryption: Cryptographic algorithms operate on bytes,
not strings.
Methods to Create Bytes
► Byte Literals: b'text data'
► bytes() Constructor:
► bytes([65, 66, 67]) -> b'ABC'
► bytes(5) -> Creates 5 null bytes: b'\x00\x00\x00\x00\x00'
► Encoding Strings: Converting text to bytes.
► 'Python'.encode('utf-8') -> b'Python'
Bytes vs. Strings (Key
Differences)
► Strings (str):
► Sequence of Unicode characters.
► Used for text storage and manipulation.
► Bytes (bytes):
► Sequence of raw 8-bit integers.
► Used for machine-level data handling.
► Conversion: Use .encode() to go from str to bytes; use
.decode() to go from bytes to str.
The Bytearray Type
► The 'bytearray' is the MUTABLE counterpart of 'bytes'.
► You can change individual bytes in a bytearray using
indexing.
► Example:
► ba = bytearray(b'Hello')
► ba[0] = 104 # Changes 'H' to 'h'
► Result: ba is now bytearray(b'hello')
Common Operations
► Indexing: Returns an integer (the ASCII value).
► b'ABC'[0] returns 65.
► Slicing: Returns a NEW bytes object.
► b'Python'[0:2] returns b'Py'.
► Join and Split: Works similarly to strings but requires
byte-type separators.
► Example: b', '.join([b'A', b'B'])
Advanced: Memoryview
► Memoryview objects allow Python code to access the
internal data of an object without copying it.
► Extremely efficient for large datasets (like image
processing).
► It works with objects that support the 'buffer protocol'
(like bytes and bytearray).
► Example: mv = memoryview(bytearray(b'ABC'))
Summary
► • bytes: Immutable sequence of 0-255 integers.
► • bytearray: Mutable sequence of 0-255 integers.
► • encode(): String to Bytes.
► • decode(): Bytes to String.
► • Essential for low-level file and network I/O.