首页 > 解决方案 > Python Construct - 如何在结构中使用按位构造

问题描述

我有这个问题,我不知道如何解决,想知道是否有人对我有提示。

这是一个简化的例子:

from construct import Struct, Enum, Byte, Switch, this, Flag

one_protocol = Struct(
    "enable" / Flag
)

protocol = Struct(
    "type" / Enum(
        Byte,
        one=0xA2,
        two=0x02,
    ),
    "data" / Switch(
        this.type,
        {
            "one": one_protocol
        }
    ),
)

input_1 = "A201"
input_2 = "A202"
print(protocol.parse(bytes.fromhex(input_1)))
print(protocol.parse(bytes.fromhex(input_2)))

它按预期工作。输出是:

Container:
    type = (enum) one 162
    data = Container:
        enable = True
Container:
    type = (enum) one 162
    data = Container:
        enable = True

问题是我希望我one_protocol在位级别上工作。更具体地说,我希望该enable字段反映第一位而不是整个字节的值。换句话说,我想enable = False获得input_2.

我知道 BitStruct 不能嵌套。但无论如何,我已经尝试将第一个替换为StructBitstruct也替换FlagBitwise(Flag).

任何想法?

标签: pythonconstruct

解决方案


Construct的作者在这里。

没有理由oneprotocol不能成为BitStruct. 您不能将 Bitwise 嵌套在另一个 Bitwise 中,但这里不是这种情况。

您不能使用Bitwise(Flag),因为按位将期望消耗所有 8 位(或 8 位的倍数),而 Flag 只需要一个。

您也无法制作protocolBitStruct,因为枚举将无法正常工作,除非您将其包装Bytewise或其他东西。


推荐阅读