Core API: Bytes and bits

construct.Bytes(length)

A field consisting of a specified number of bytes. Builds from a b-string, or an integer (although deprecated and BytesInteger should be used).

See also

Analog BytesInteger() that parses and builds from integers.

Parameters:length – an int or a function that takes context and returns int

Example:

>>> Bytes(4).parse(b"beef")
b'beef'
>>> Bytes(4).build(_)
b'beef'
>>> Bytes(4).build(255)
b'\x00\x00\x00\xff'
>>> Bytes(4).sizeof()
4
construct.GreedyBytes()

A byte field, that parses the stream to the end and builds into the stream as-is.

This is an analog to Bytes(infinity), pun intended.

See also

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

Example:

>>> GreedyBytes.parse(b"helloworld")
b'helloworld'
>>> GreedyBytes.build(b"asis")
b'asis'
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.

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

Example:

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

A byte field, that parses into and builds from integers as opposed to b-strings. This is 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, or a function that takes context and returns int
  • 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)
  • bytesize – size of byte as used for byte swapping (if swapped), default is 1

Example:

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

A byte field, that parses into and builds from integers as opposed to b-strings. This is similar to Bit/Nibble/Octet fields but can have arbitrary sizes. This must be enclosed in Bitwise.

Parameters:
  • length – number of bits in the field, or a context function that returns int
  • 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)
  • bytesize – size of byte as used for byte swapping (if swapped), default is 8

Example:

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