[英]Python Construct - How to use a bitwise construct inside a struct
I have this problem that I can't figure out how to solve and was wondering if anyone has a hint for me.我有这个问题,我不知道如何解决,想知道是否有人对我有提示。
This is a simplified example:这是一个简化的例子:
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)))
And it works as expected.它按预期工作。 The output is: output 是:
Container:
type = (enum) one 162
data = Container:
enable = True
Container:
type = (enum) one 162
data = Container:
enable = True
The problem is that I want my one_protocol
to work in bit level.问题是我希望我的one_protocol
在位级别工作。 More specifically, I want the enable
field to reflect the value of the first bit and not the whole byte.更具体地说,我希望enable
字段反映第一位而不是整个字节的值。 In other words, I want to get enable = False
for input_2
.换句话说,我想为input_2
获得enable = False
。
I know that BitStruct cannot be nested.我知道 BitStruct 不能嵌套。 But anyway, I have tried replacing the first Struct
with Bitstruct
and also replace Flag
with Bitwise(Flag)
.但无论如何,我已经尝试用Bitstruct
替换第一个Struct
并用Bitwise(Flag)
替换Flag
。
Any idea?任何想法?
Construct's author here. Construct的作者在这里。
There is no reason why oneprotocol
cannot be a BitStruct
. oneprotocol
没有理由不能是BitStruct
。 You cannot nest Bitwise in another Bitwise but that is not the case here.您不能将 Bitwise 嵌套在另一个 Bitwise 中,但这里不是这种情况。
You cannot use Bitwise(Flag)
because Bitwise will expect all 8 bits (or a multiple of 8 bits) to be consumed while Flag only takes one.您不能使用Bitwise(Flag)
因为 Bitwise 将期望消耗所有 8 位(或 8 位的倍数),而 Flag 只需要一个。
You also cannot make protocol
a BitStruct because then enum will not work properly, unless you wrap it with Bytewise
or something.您也不能将protocol
设置为 BitStruct,因为这样枚举将无法正常工作,除非您将其包装为Bytewise
或其他东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.