使用 Python 中的 struct 模块可以方便地对数字列表进行 bytearray 编码和解码。

编码步骤:

  1. 将数字列表转换为二进制字符串(例如使用 bin() 函数)。
  2. 根据数据类型,使用 struct.pack() 函数将二进制字符串打包为字节对象 (bytearray)。

解码步骤:

  1. 使用 struct.unpack() 函数,按照相应的格式解包 bytearray 对象,得到一个元组。
  2. 遍历元组,将每个元素转换为相应的数据类型,得到解码后的数字列表。

示例代码:

import struct

# 编码
num_list = [1, 2, 3, 4]
bn_str = ''.join([bin(num)[2:].zfill(32) for num in num_list])
byte_arr = bytearray(int(bn_str[i:i+8], 2) for i in range(0, len(bn_str), 8))

# 解码
fmt = '>{}i'.format(len(num_list))  # '>4i'
unpacked = struct.unpack(fmt, byte_arr)
decoded_list = list(unpacked)

print(decoded_list)  # [1, 2, 3, 4]

在上面的代码中,我们将数字列表 [1, 2, 3, 4] 转换为二进制字符串 '0000000000000000000000000000000100000000000000000000000000000010000000000000000000000000000001100000000000000000000000000000100',然后将它打包为一个长度为 16 的 bytearray 对象。接着使用 '>4i' 的格式字符串解包 byte_arr,得到一个元组 (1, 2, 3, 4),最后将元组转换为列表即可。

Python bytearray 编码解码数字列表:使用 struct 模块

原文地址: https://www.cveoy.top/t/topic/mSRD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录