- Muchas notas - Fran Acién

20230510 - Python Construct - Binary data structure parser

This python library is used to describe binary data structures.

For binary structures you can use Bitstructs.

Another project similar to construct is Kaitai, that is used a lot of satnogs. Here is a comparison between both. Kaitai is only for parsin, not for creating binary data. 20230511 - Binary data structures with Kaitai and python

Data types

All integers follow the Int{8,16,24,32,64}{u,s}{b,l,n} and floats follow the Float{16,32,64}{b,l} naming patterns.

It is easy to see all the data structues by writting “from construct import *” and see the imported variables.

Examples of binary structures

from construct import Struct, BitStruct, BitsInteger, Int8ul, Int16ul

CCSDS_primary_header = BitStruct(
  "version" / BitsInteger(3),
  "type" / BitsInteger(1),
  "sec_header_flag" / BitsInteger(1),
  "proc_id" / BitsInteger(11),
  "seq_flags" / BitsInteger(2),
  "seq_cnt" / BitsInteger(14),
  "length" / BitsInteger(16)
  )

CCSDS_secondary_header = Struct(
  "epoch" / Int8ul,
  "majorVersionNumber" / Int8ul,
  "patchVersionNumber" / Int8ul
  )

CCSDS_packet = Struct(
  "CCSDS_primary_header" / CCSDS_primary_header,
  "CCSDS_secondary_header" / CCSDS_secondary_header
  )

a = CCSDS_primary_header.build(dict(
  version = 2,
  type = 1,
  sec_header_flag = 0,
  proc_id = 0,
  seq_flags = 0,
  seq_cnt = 0,
  length = 1
  ))

b = CCSDS_secondary_header.build(dict(
  epoch = 1,
  majorVersionNumber = 2,
  patchVersionNumber = 3,
  ))

c = CCSDS_packet.build(dict(
  CCSDS_primary_header = dict(
    version = 2,
    type = 1,
    sec_header_flag = 0,
    proc_id = 0,
    seq_flags = 0,
    seq_cnt = 0,
    length = 1
    ),
  CCSDS_secondary_header = dict(
    epoch = 1,
    majorVersionNumber = 2,
    patchVersionNumber = 3,
    )
  ))

print(a.hex())
print(b.hex())
print(c.hex())