Python Bytes

字节操作

字节类

python 中处理字节有两种类型,bytesbytearray 类。两者都是序列,前者类似元组(不可更改),后者类似列表。

Bytes Class

bytesstr 类相似。创建方法:

  1. 由字符创建(ASCII 码),b'{text here}'
  2. From an iterable of integers: bytes(range(20))
  3. A zero-filled bytes object of a specified length: bytes(10)

bytes 可以与16进制互相转换。(.fromhex().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

参考字符串操作。

转换

将 Python 其余数据类型转换为 Bytes

Numpy

np.tobytes()np.ndarray 转换为字节串,按照行主格式。

x = np.array([[0, 1], [2, 3]], dtype='<u2') # 小端,无符号整形,两个字节
x.tobytes()
# b'\x00\x00\x01\x00\x02\x00\x03\x00'

np.frombuffer() 将字节串转换为np.ndarray

np.frombuffer(b'\x01\x02', dtype=np.uint8)
# array([1, 2], dtype=uint8)

两者配合

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, ...)struct.unpack(format, buffer)

Format

format 中一位对应后面一个值,与 C 类似。

pack('hhl', 1, 2, 3)
# b'\x00\x01\x00\x02\x00\x00\x00\x03'

unpack 返回是元组,每个元素与format 一一对应。

猜你喜欢

转载自blog.csdn.net/lib0000/article/details/114012181