Core API: Bytes and bits

construct.Bytes(length)

Field consisting of a specified number of bytes. Builds from a bytes, or an integer (although deprecated and BytesInteger should be used instead).

See also

Analog BytesInteger() that parses and builds from integers, as opposed to bytes.

Parameters:length – an integer or a context lambda that returns such an integer

Example:

>>> d = Bytes(4)
>>> d.parse(b'beef')
b'beef'
>>> d.build(b'beef')
b'beef'
>>> d.build(0)
b'\x00\x00\x00\x00'
>>> d.sizeof()
4
construct.GreedyBytes()

Field that parses the stream to the end and builds into the stream as is.

See also

Analog GreedyString() that parses and builds from strings using an encoding.

Example:

>>> GreedyBytes.parse(b"asislight")
b'asislight'
>>> GreedyBytes.build(b"asislight")
b'asislight'
construct.Bitwise(subcon)

Converts the stream from bytes to bits, and passes the bitstream to underlying subcon.

See also

Analog Bytewise() that transforms subset of bits back to bytes.

Warning

Do not use pointers inside this or other restreamed contexts.

Parameters:subcon – any field that works with bits like BitStruct or Bit Nibble Octet BitsInteger

Example:

>>> d = Bitwise(Octet)
>>> d.parse(b"\xff")
255
>>> d.build(1)
b'\x01'
>>> d.sizeof()
1
construct.BytesInteger(length, signed=False, swapped=False)

Field that builds from integers as opposed to bytes. Similar to Int* fields but can have arbitrary size.

See also

Analog BitsInteger() that operates on bits.

Parameters:
  • length – number of bytes in the field, and integer or a context function that returns such an integer
  • signed – whether the value is signed (two’s complement), default is False (unsigned)
  • swapped – whether to swap byte order (little endian), default is False (big endian)

Example:

>>> d = BytesInteger(4) or Int32ub
>>> d.parse(b"abcd")
1633837924
>>> d.build(1)
b'\x00\x00\x00\x01'
>>> d.sizeof()
4
construct.BitsInteger(length, signed=False, swapped=False)

Field that builds from integers as opposed to bytes. Similar to Bit/Nibble/Octet fields but can have arbitrary sizes. Must be enclosed in Bitwise.

Parameters:
  • length – number of bits in the field, an integer or a context function that returns such an integer
  • signed – whether the value is signed (two’s complement), default is False (unsigned)
  • swapped – whether to swap byte order (little endian), default is False (big endian)

Example:

>>> d = Bitwise(BitsInteger(8))
>>> d.parse(b"\x10")
16
>>> d.build(255)
b'\xff'
>>> d.sizeof()
1