问题描述
这是一个简化的例子:
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 不能嵌套。但无论如何,我已尝试将第一个 Struct
替换为 Bitstruct
,并将 Flag
替换为 Bitwise(Flag)
。
有什么想法吗?
解决方法
这里是构造的作者。
没有理由说明 oneprotocol
不能是 BitStruct
。您不能将 Bitwise 嵌套在另一个 Bitwise 中,但这里的情况并非如此。
您不能使用 Bitwise(Flag)
,因为 Bitwise 会期望消耗所有 8 位(或 8 位的倍数),而 Flag 只需要一个。
您也不能将 protocol
设为 BitStruct,因为这样枚举将无法正常工作,除非您用 Bytewise
或其他东西将其包装起来。