如何构造具有可变大小元素的数据结构

2024-04-18 19:41:17 发布

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

我试图用类val中的元素value的可变大小构造结构:

from construct import *

TEST = Struct("test",
           UInt8("class"),
           Embed(switch(lambda ctx: ctx.class) {
             1: UInt8("value"),
             2: UInt16("value"),
             3: UInt32("value")}
            ))
          )

以上代码不正确。你知道吗

我需要实现这样的功能:如果类是1,那么将从数据包接收一个字节。你知道吗


Tags: fromtestimport元素valuevalembedconstruct
1条回答
网友
1楼 · 发布于 2024-04-18 19:41:17

您可以使用多个format string来更改struct行为,并使用struct.calcsize来继续从最后找到的字节序列的末尾分析bytearray:

import struct
v1 = bytearray([0x00,0xFF])
v2 = bytearray([0x01,0xFF,0xFF])
v3 = bytearray([0x02,0xFF,0xFF,0xFF,0xFF])

v = v2 # change this

header_format = 'B'
body_format_variants = {0:'B',1:'H',2:'L'}

header = struct.unpack_from(header_format,v,0)
body = struct.unpack_from(body_format_variants[header[0]],v,struct.calcsize(header_format))

print (header, body, "size=",struct.calcsize('>'+header_format+body_format_variants[header[0]]))

相关问题 更多 >