简体   繁体   中英

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 for length = 24 bits; value length = 3 octets for length = 17 bits; value length = 3 octets for length = 31 bits; value length = 4 octets 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.

实际的问题是YAML解析器,因为它在:符号处打断了表达式,解决方案是将表达式放入这样的引号中:

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

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) + " ..."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM