Core API: Alignment and Padding

construct.Padding(length, pattern='\x00', strict=False)

A padding field that adds bytes when building, discards bytes when parsing.

Parameters:
  • length – length of the padding, an int or a function taking context and returning an int
  • pattern – padding pattern as b-string character, default is b”x00” null character
  • strict – whether to verify during parsing that the stream contains the pattern, raises an exception if actual padding differs from the pattern, default is False

Example:

>>> (Padding(4) >> Bytes(4)).parse(b"????abcd")
[None, b'abcd']
>>> (Padding(4) >> Bytes(4)).build(_)
b'\x00\x00\x00\x00abcd'
>>> (Padding(4) >> Bytes(4)).sizeof()
8

>>> Padding(4).build(None)
b'\x00\x00\x00\x00'
>>> Padding(4, strict=True).parse(b"****")
construct.core.PaddingError: expected b'\x00\x00\x00\x00', found b'****'
construct.Padded(length, subcon, pattern='\x00', strict=False)

Appends additional null bytes to achieve a fixed length.

Example:

>>> Padded(4, Byte).build(255)
b'\xff\x00\x00\x00'
>>> Padded(4, Byte).parse(_)
255
>>> Padded(4, Byte).sizeof()
4

>>> Padded(4, VarInt).build(1)
b'\x01\x00\x00\x00'
>>> Padded(4, VarInt).build(70000)
b'\xf0\xa2\x04\x00'
construct.Aligned(modulus, subcon, pattern='\x00')

Appends additional null bytes to achieve a length that is shortest multiple of a modulus.

Parameters:
  • modulus – the modulus to final length, an int or a context->int function
  • subcon – the subcon to align
  • pattern – optional, the padding pattern (default is x00)

Example:

>>> Aligned(4, Int16ub).build(1)
b'\x00\x01\x00\x00'
>>> Aligned(4, Int16ub).parse(_)
1
>>> Aligned(4, Int16ub).sizeof()
4