Core API: Integers and Floats

construct.FormatField(endianity, format)

Field that uses struct module to pack and unpack data. This is used to implement basic Int* and Float* fields alongside BytesInteger.

See struct documentation for instructions on crafting format strings.

Parameters:
  • endianity – endianness character like < > =
  • format – format character like f d B H L Q b h l q

Example:

>>> d = FormatField(">", "H")
>>> d.parse(b"\x01\x00")
256
>>> d.build(256)
b"\x01\x00"
>>> d.sizeof()
2
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
construct.VarInt()

Varint encoded integer. Each 7 bits of the number are encoded in one byte of the stream, where leftmost (MSB) bit is unset when byte is terminal.

Can only encode non-negative numbers.

Scheme defined at Google’s site: https://developers.google.com/protocol-buffers/docs/encoding https://techoverflow.net/blog/2013/01/25/efficiently-encoding-variable-length-integers-in-cc/

Example:

>>> VarInt.build(16)
b'\x10'
>>> VarInt.build(2**100)
b'\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x04'