Python Bytes

Byte operation

Byte class

python byte processing two types, bytesand bytearrayclass. Both are sequences, the former is similar to a tuple (unchangeable), and the latter is similar to a list.

Bytes Class

bytesAnd strsimilar classes. Creation method:

  1. Created by characters (ASCII code),b'{text here}'
  2. From an iterable of integers: bytes(range(20))
  3. A zero-filled bytes object of a specified length: bytes(10)

bytesCan be converted to hexadecimal. ( .fromhex()And .hex()).

Bytearray Class

  1. Creating an empty instance: bytearray(3)(a three elements byte array)
  2. Creating a zero-filled instance with a given length: bytearray(10)
  3. From an iterable of integers: bytearray(range(20))
  4. 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.ndarrayconvert 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'

unpackThe return is a tuple, each element formatcorresponds to a one-to-one.

Guess you like

Origin blog.csdn.net/lib0000/article/details/114012181