Article Directory
Byte operation
Byte class
python byte processing two types, bytes
and bytearray
class. Both are sequences, the former is similar to a tuple (unchangeable), and the latter is similar to a list.
Bytes Class
bytes
And str
similar classes. Creation method:
- Created by characters (ASCII code),
b'{text here}'
- From an iterable of integers:
bytes(range(20))
- A zero-filled bytes object of a specified length:
bytes(10)
bytes
Can be converted to hexadecimal. ( .fromhex()
And .hex()
).
Bytearray Class
- Creating an empty instance:
bytearray(3)
(a three elements byte array) - Creating a zero-filled instance with a given length:
bytearray(10)
- From an iterable of integers:
bytearray(range(20))
- Copying existing binary data via the buffer protocol:
bytearray(b'Hi!')
Common Operations
Refer to string operations.
Conversion
Convert the rest of Python data types to Bytes
Numpy
np.tobytes()
It will np.ndarray
convert byte string, in row major format.
x = np.array([[0, 1], [2, 3]], dtype='<u2') # 小端,无符号整形,两个字节
x.tobytes()
# b'\x00\x00\x01\x00\x02\x00\x03\x00'
np.frombuffer()
Convert the byte string to np.ndarray
.
np.frombuffer(b'\x01\x02', dtype=np.uint8)
# array([1, 2], dtype=uint8)
The two work together
x = np.array([[0, 1], [2, 3]], dtype='<u2') # 小端,无符号整形,两个字节
y = x.tobytes()
x_flat = np.frombuffer(y, dtype=np.uint16)
# np.ndarray([0, 1, 2, 3])
Struct
struct.pack(format, v1, v2, ...)
With struct.unpack(format, buffer)
.
Format
format
One bit corresponds to the next value, similar to C.
pack('hhl', 1, 2, 3)
# b'\x00\x01\x00\x02\x00\x00\x00\x03'
unpack
The return is a tuple, each element format
corresponds to a one-to-one.