You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Kaitai Struct编写可重复解析的基础TLV解析器?

解决Kaitai Struct循环解析TLV至文件末尾的问题

问题背景

需要解析一种重复至文件末尾的TLV格式,结构为:

  • 1字节标签(tag)
  • 1字节长度(length,单位为字节)
  • 对应长度的数据字节

现有Kaitai定义仅能解析第一个TLV条目,无法循环处理剩余内容,需调整定义实现全文件解析。

修改后的Kaitai定义

meta:
  id: basictlv
  endian: le
types:
  tlv_entry:
    seq:
      - id: type_tag
        type: u1
      - id: body
        type:
          switch-on: type_tag
          cases:
            1: bunch_of_ones
            2: bunch_of_twos
  bunch_of_ones:
    seq:
      - id: how_many_1
        type: u1
      - id: ones
        size: how_many_1
  bunch_of_twos:
    seq:
      - id: how_many_2
        type: u1
      - id: twos
        size: how_many_2
seq:
  - id: tlv_entries
    type: tlv_entry
    repeat: eos

关键改动说明

  1. 封装单个TLV单元:新增tlv_entry类型,将原顶层的type_tag和body逻辑移入其中,作为单个TLV的完整结构。
  2. 循环解析至文件末尾:顶层序列定义tlv_entries数组,使用repeat: eos关键字,让解析器重复读取tlv_entry类型的数据,直到文件流结束。

测试验证

测试文件的十六进制内容:

$ xxd simple-tlv-file.dat
00000000: 0102 0101 0203 0202 0203 0103            ............

使用修改后的定义解析,ksdump输出结果:

tlv_entries:
  - body:
      how_many_1: 2
      ones: 01 01
    type_tag: 1
  - body:
      how_many_2: 3
      twos: 02 02 02
    type_tag: 2
  - body:
      how_many_1: 3
      ones: 03 01 03
    type_tag: 1

内容的提问来源于stack exchange,提问作者ixe013

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:35:13