kaitai-struct

Capture a three bytes two's complement signed integer with Kaitai


Kaitai Struct offers predefined types to capture, for example, signed 2-bytes integers (s2be) or signed 4-bytes integers (s4be) but there is no s3be and b24 captures 3-bytes unsigned integer (http://doc.kaitai.io/ksy_reference.html#_bit_size_integers). Is there a way to do it?

field_a:
    seq:
      - id: two
        type: s2be
      - id: three
        type: ???
      - id: four
        type: s4be

Solution

  • There are multiple ways to do that. For example, you can use something like this to convert unsigned to signed:

    seq:
      - id: three
        type: s3be
    types:
      s3be:
        seq:
          - id: unsigned_value
            type: b24
        instances:
          value:
            value: '(unsigned_value & 0x800000 != 0) ? (~(unsigned_value & 0x7fffff)) : unsigned_value'
    

    Note that it will be user type, so to get to the value of the integer, you'll need to use three.value, not just three.