我有一个包含各种数据的类,比如:
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字节的数据块中读取数据,我需要拆分它。我尝试过pickle库,但它似乎不完全适合反序列化这种类型的数据。我找到了struct,但我不明白在这种情况下如何恰当地使用它。
作为结构中的注释,我需要去搜索数据块,比如:第一个字节是标识符,从1到5的字节是时间戳,等等……
你有什么想法吗?我该怎么做?
谢谢
首先,我们需要根据这个列表声明传入字节的格式:https://docs.python.org/3/library/struct.html?highlight=struct#format-characters。在
fmt
的第一个字符是字节顺序。@
是python的默认值(通常是little-endian),如果您需要使用network big-endian-put!
。每个后续字符表示来自字节流的数据类型。在接下来,在初始值设定项中,我根据}作为第二个参数)。在
fmt
中的配方将字节解压到fields
元组中。接下来,我将元组的值赋给对象属性。时间戳的异常长度为5个字节,因此需要特殊处理。它作为5字节字符串(fmt中的5s
)被获取,并使用系统默认字节顺序的int.from_bytes
函数转换为int(如果需要不同的字节顺序,请输入'big'
或{当你想创建你的结构时,把字节序列传递给构造函数。在
相关问题 更多 >
编程相关推荐