javabinarykaitai-struct

Using ternary operator to calculate the length


I have a binary structure that has a length field in bits and the value field corresponding to that length. The value length is filled up with enough trailing bits to make the end of the field fall on an octet boundary. I need to calculate that that length, so for example: for length = 24 bits; value length = 3 octets for length = 17 bits; value length = 3 octets for length = 31 bits; value length = 4 octets etc.

As I read in documentation it is possible to use ternary operator in .ksy file. So I have the following expression to calculate value field size:

size: length % 8 == 0 ? length / 8 : length / 8 + 1

This expression works perfectly in Kaitai WebIDE, but when I try to generate the java class with:

kaitai-struct-compiler -t java --java-package com.my.struct.package --verbose file mystruct.ksy

I receive the following error:

parsing mystruct.ksy...
reading mystruct.ksy...
mapping values are not allowed here
 in 'reader', line 194, column 44:
     ... e: length % 8 == 0 ? length / 8 : length / 8 + 1
                                         ^

I have also tried to calculate the value for the additional octet in separate calculated value like this:

...
      - id: prefix
        size: length / 8 + additional_octet

    instances:
      additional_octet:
        value: (length % 8 == 0 ? 0 : 1)
...

But the same error occurs.


Solution

  • Simplify and a ternary is not needed:

    size: (length + 7) / 8
    

    Not having used kaitai struct, I more have my doubts on using an expression as such; I would have expected code here:

    "... size: " + ((length + 7) / 8) + " ..."