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

2024-10-03 04:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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的字节是时间戳,等等……
你有什么想法吗?我该怎么做?
谢谢


Tags: 数据字节bytes序列化序列byte结构class
1条回答
网友
1楼 · 发布于 2024-10-03 04:27:10

首先,我们需要根据这个列表声明传入字节的格式: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-put!。每个后续字符表示来自字节流的数据类型。在

接下来,在初始值设定项中,我根据fmt中的配方将字节解压到fields元组中。接下来,我将元组的值赋给对象属性。时间戳的异常长度为5个字节,因此需要特殊处理。它作为5字节字符串(fmt中的5s)被获取,并使用系统默认字节顺序的int.from_bytes函数转换为int(如果需要不同的字节顺序,请输入'big'或{}作为第二个参数)。在

当你想创建你的结构时,把字节序列传递给构造函数。在

相关问题 更多 >