sample_python_construct.py 608 B

12345678910111213141516
  1. # Inspired from https://construct.readthedocs.io/en/latest/intro.html#example
  2. import construct
  3. format = construct.Struct(
  4. "signature" / construct.Const(b"BMP"),
  5. "width" / construct.Int8ub,
  6. "height" / construct.Int8ub,
  7. "pixels" / construct.Array(construct.this.width * construct.this.height, construct.Byte),
  8. )
  9. a = format.build(dict(width=3,height=2,pixels=[7,8,9,11,12,13]))
  10. assert(a == b'BMP\x03\x02\x07\x08\t\x0b\x0c\r')
  11. b = format.parse(b'BMP\x03\x02\x07\x08\t\x0b\x0c\r')
  12. assert(b.signature == b'BMP')
  13. assert(b.width == 3)
  14. assert(b.height == 2)
  15. assert(b.pixels == [7, 8, 9, 11, 12, 13])