Skip to content

Ability to sum array elements in Kaitai Struct #1230

Open
@tetelevm

Description

@tetelevm

I have two similar problems. The first one: I need int of sizes other than u1, u2, u4, and u8. I created a custom u3 type that fits my needs:

types:
  u3:
    seq:
      - id: b0
        type: u1
      - id: b1
        type: u1
      - id: b2
        type: u1
    instances:
      le:
        value: (b0 << 16) + (b1 << 8) + b2
      be:
        value: b0 + (b1 << 8) + (b2 << 16)

seq:
  - id: my_val
    type: u3
instances:
  le:
    value: my_val.le
  be:
    value: my_val.be

# in: hex("01 02 03")
# out: le == 66051
# out: be == 197121

The problem is that using other sizes requires duplicating code. Is there any way to generalize the creation of such types? Something like this:

type:
  byte_type:
    params:
      - id: size
        type: u1
      - id: index
        type: u1
    seq:
      - id: byte
        type: u1
    instances:
      le:
        value: byte << ((size-index) * 8)
      be:
        value: byte << (index * 8)
  u:
    params:
      - id: size
        type: u1
    seq:
      - id: bytes
        type: byte_type(len, _index)
        repeat: expr
        repeat-expr: size
    instances: 
      le:
        value: sum(bytes.le) # ???
      be:
        value: sum(bytes.be) # ???

So that later I could define it simply like this:

seq:
  - id: data0
    type: u(3)
  - id: data1
    type: u(5)
instances:
  data0_le:
    value: data0.le
  data1_le:
    value: data1.be

# in: hex("010203 0405060708")
# out: data0_le == 66051
# out: data1_le == 17264150280

Is it possible to reproduce the effect of sum(bytes.be) in Kaitai?

The second problem is quite similar, but this time I need to concatenate an array of strings (concatenate(["01", "02", "03"]) # => "010203").

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions