我是靠谱客的博主 舒服雨,这篇文章主要介绍Python Bytes字节操作,现在分享给大家,希望可以做个参考。

文章目录

  • 字节操作
    • 字节类
      • Bytes Class
      • Bytearray Class
      • Common Operations
    • 转换
      • Numpy
      • Struct
      • Format

字节操作

字节类

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 转换为字节串,按照行主格式。

复制代码
1
2
3
4
x = np.array([[0, 1], [2, 3]], dtype='<u2') # 小端,无符号整形,两个字节 x.tobytes() # b'x00x00x01x00x02x00x03x00'

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

复制代码
1
2
3
np.frombuffer(b'x01x02', dtype=np.uint8) # array([1, 2], dtype=uint8)

两者配合

复制代码
1
2
3
4
5
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])
  • Example: ROS 点云转换

ROS 中点云一般是字节串形式接受,规定了编码格式。一般是一小块中包含了 x, y, z 的信息。可以用 Numpy 快速解码

复制代码
1
2
3
4
5
6
7
8
9
10
# 假设就一个点 (0, 1, 2) a = np.arange(3) b = a.tobytes() # 定义每个数据块的格式 data_type=np.dtype([('x', np.int64), ('y', np.int64), ('z', np.int64)]) c = np.frombuffer(a, dtype=data_type) c['x'] # x 信息

Struct

struct.pack(format, v1, v2, ...)struct.unpack(format, buffer)

Format

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

复制代码
1
2
3
pack('hhl', 1, 2, 3) # b'x00x01x00x02x00x00x00x03'

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

最后

以上就是舒服雨最近收集整理的关于Python Bytes字节操作的全部内容,更多相关Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(77)

评论列表共有 0 条评论

立即
投稿
返回
顶部