Python provides two built-in types to work with binary data: bytes
and bytearray
. Both types represent sequences of bytes, with bytes
being immutable and bytearray
being mutable.
To create a bytes
object, you can simply enclose a sequence of bytes in single quotes b''
or double quotes b""
:
main.py96 chars6 lines
Alternatively, you can use the bytes()
constructor to create a bytes
object:
main.py47 chars4 lines
To modify binary data, you can use bytearray
s:
main.py144 chars5 lines
When working with binary data, you may need to pack and unpack binary data representing C structs. Python provides the struct
module for this purpose:
main.py258 chars8 lines
In this example, the pack()
method takes a format string ('hhl'
) and a set of values to pack. The format string specifies the type and ordering of the values. The unpack()
method does the opposite, taking a format string and a bytes object and returning a tuple of the unpacked values.
gistlibby LogSnag