btl.bitload

This module contains the bitload class which is used to serialize and deserialize python values.

class btl.bitload.Bitload(description, autopad=True)

This class returns an object that is used to serialize and deserialize python values. The object is instantiated with the bitload description and maintains a map of the bitload layout. This map is used by its methods to insert or extract regions of the binary data that belong to individual fields.

The bitload layout is accessible through the layout property, which is an instance of collections.OrderedDict. The keys correspond to field names, and the values are namedtuple instances with the following attributes:

  • start: starting index of the field
  • end: index one after the final index of the field
  • length: length of the field (in bits)
  • serializer: function used for serializing the python value of the field
  • deserializer: function used for deserializing the binary data into the python value of the field

These attributes are read-only and cannot be assigned to.

After the layout is processed, the object’s length property is set to the total length of the bitload.

Warning

The object’s length property is not read-only, but you should not try to change its value unless you know exactly what you are doing.

By default, the length of the bitload is automatically padded to whole bytes. To disable the padding, we can pass autopad=False to the constructur, in which case the length of the bitload is a simple sum of lengths of the fields (incuding ‘pad’ fields).

deserialize(bitload)

Return a OrderedDict object that contains the data from the specified bitload. The bitload argument should be a bytestring.

If the bitload does not have the correct length, a ValueError exception is raised.

serialize(data)

Return a bytestring containing serialized and packed data. The data object must be a dictionary or a dict-like object that implements key access.

btl.bitload.deserialize(description, bitload, padded=True)

Return an OrderedDict object using the specified bitload description and bitload. This is a shortcut for instantiating a Bitload object and calling its deserialize() method.

The padded argument is used to specify whether the incoming bitload has been padded to whole bytes.

btl.bitload.serialize(description, data, autopad=True)

Return a serialized bytestring using the specified bitload description and data. This is a shortcut for instantiating a Bitload object and calling its serialize() method.

The autopad argument can be used to automatically pad the bitload to whole bytes.