python - 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 不能嵌套。但无论如何,我已经尝试将第一个替换为Struct
,Bitstruct
也替换Flag
为Bitwise(Flag)
.
任何想法?
解决方案
Construct的作者在这里。
没有理由oneprotocol
不能成为BitStruct
. 您不能将 Bitwise 嵌套在另一个 Bitwise 中,但这里不是这种情况。
您不能使用Bitwise(Flag)
,因为按位将期望消耗所有 8 位(或 8 位的倍数),而 Flag 只需要一个。
您也无法制作protocol
BitStruct,因为枚举将无法正常工作,除非您将其包装Bytewise
或其他东西。
推荐阅读
- az - az sql server ad-admin create 在 azure devops 中失败,出现 puython 错误
- javascript - ReactJs:如何构建 npm 库
- javascript - Node 应用程序的 Heroku 部署返回 node-waf: not found
- python - 从 Numpy 数组或 Python 列表中删除前导的 None 项
- sql - 仅显示每种类型的传感器 sql 问题中的一种
- python - python matplotlib plotly graph_objects 如何保存图形
- sql - 基于行间共享属性的新ID
- python - 如何解决“DataFrame”对象没有属性“column_name”?
- python - 尝试查找长度为 6 的列表的值 1 时,Python 列出“列表索引超出范围”错误
- vim - 如何在vim中重复查找/替换命令