python 中的数据格式二进制模式描述和解码

Data format binary schema description and decoding in python

我正在创建一些 python 脚本来解码各种二进制格式。 每种格式都有很多不同的记录,并且相当多的数据被编码在特定字节内的特定位范围内。 因此,我正在寻找一个 python 包,它可以将解码代码和格式规范巧妙地分开,这样代码就不会变得太乱。 理想情况下,它会让我保留不同版本的格式。 下面是我正在寻找的一个非常粗略的轮廓。

示例my_data_format.xml

<format version="1A">
  <record name="My first record">
    <ignore bytes="2" />
    <field name="A simple number" bytes="1" convert_to="int" />
    <field name="A simple float" bytes="4" convert_to="float" />
    <array name="A list of floats" length="3">
      <field bytes="4" convert_to="float"
    </array>
    <field bytes="2">
      <ignore bits="5" />
      <bitfield name="First bit-field" num_bits="6" convert_to="uint8" />
      <bitfield name="Second bit-field" num_bits="5" convert_to="float" />
    </field>
  </record>
</format>

示例 python 脚本 my_data_reader.py:

from binary_schema import load_schema

schema = load_schema('my_data_format.xml')

with open(̈́'myfile.bin', 'rb') as f:
  decoded_data = schema.read_record_from_stream('Record header', f)

print(decoded_data)

这会产生一个字典:

{'A simple float': 3.234,
 'A simple number': 3,
 'A list of floats': [1., 2., 3.],
 'First bit-field': 3,
 'Second bit-field': 2.0}

有这种东西吗?

我已经看过一些东西了:

查看 https://kaitai.io/ "Kaitai Struct: A new way to develop parsers for binary structures."

我想您会发现它会满足您的需求,架构不是 XML,但我认为格式也比 XML 灵活得多。