簡體   English   中英

Python 構造 - 如何在結構中使用按位構造

[英]Python Construct - How to use a bitwise construct inside a struct

我有這個問題,我不知道如何解決,想知道是否有人對我有提示。

這是一個簡化的例子:

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)))

它按預期工作。 output 是:

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

問題是我希望我的one_protocol在位級別工作。 更具體地說,我希望enable字段反映第一位而不是整個字節的值。 換句話說,我想為input_2獲得enable = False

我知道 BitStruct 不能嵌套。 但無論如何,我已經嘗試用Bitstruct替換第一個Struct並用Bitwise(Flag)替換Flag

任何想法?

Construct的作者在這里。

oneprotocol沒有理由不能是BitStruct 您不能將 Bitwise 嵌套在另一個 Bitwise 中,但這里不是這種情況。

您不能使用Bitwise(Flag)因為 Bitwise 將期望消耗所有 8 位(或 8 位的倍數),而 Flag 只需要一個。

您也不能將protocol設置為 BitStruct,因為這樣枚舉將無法正常工作,除非您將其包裝為Bytewise或其他東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM