gpt4 book ai didi

python - 在 python 中使用 struct 反序列化来自串行的字节数组

转载 作者:行者123 更新时间:2023-11-28 22:34:38 25 4
gpt4 key购买 nike

我有一个包含各种数据的类,例如:

class UARTMessage:
Identification1 = int(0) #byte 0
Timestamp1 = int(0) #bytes [1:5]
Voltage1 = int(0) #bytes [6:7]
Current1 = int(0) #bytes [8:9]
Signal1= int(0) #bytes [10:11]
Identification2 = int(0) #byte 12
Timestamp2 = int(0) #bytes [13:17]
Voltage2 = int(0) #bytes [18:19]
Current2 = int(0) #bytes [20:21]
Signal = int(0) #bytes [22:23]
Identification3 = int(0) #byte 24

填充此结构的数据将来自序列。我需要以这种结构的形式反序列化来自序列的数据。我正在读取连续的 40 字节数据 block ,我需要拆分它。我尝试了 pickle 库,但它似乎不适合反序列化此类数据。我找到了 struct但我不明白在这种情况下如何正确使用它。
作为结构中的注释,我需要对数据 block 进行反序列化,例如:第一个字节是标识符,从 1 到 5 的字节是时间戳等等....
你有什么想法我怎样才能做到这一点?
谢谢

最佳答案

首先,我们需要根据这个列表声明传入字节的格式:https://docs.python.org/3/library/struct.html?highlight=struct#format-characters .

import struct
import sys


class UARTMessage:

fmt = '@B5shhhB5shhhB'

def __init__(self, data_bytes):
fields = struct.unpack(self.fmt, data_bytes)
(self.Identification1,
self.Timestamp1,
self.Voltage1,
self.Current1,
self.Signal1,
self.Identification2,
self.Timestamp2,
self.Voltage2,
self.Current2,
self.Signal2,
self.Identification3) = fields
self.Timestamp1 = int.from_bytes(self.Timestamp1, sys.byteorder)
self.Timestamp2 = int.from_bytes(self.Timestamp2, sys.byteorder)
self.Timestamp3 = int.from_bytes(self.Timestamp3, sys.byteorder)

fmt 的第一个字符是字节顺序。 @是python默认的(通常是little endian),如果你需要使用network big-endian就放!。每个后续字符代表一个来自字节流的数据类型。

接下来,在初始化程序中,我根据 fmt 中的配方将字节解压缩到 fields 元组中。接下来,我将元组的值分配给对象属性。 Timestamp 有 5 个字节的特殊长度,因此需要特殊处理。它作为 5 字节字符串(fmt 中的 5s)获取,并使用 int.from_bytes 函数以系统默认字节顺序转换为 int(如果您需要不同的字节顺序,请输入'big''little' 作为第二个参数)。

当您想要创建结构时,将字节序列传递给构造函数。

关于python - 在 python 中使用 struct 反序列化来自串行的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38829921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com