Skip to main content
Join the official 2020 Python Developers SurveyStart the survey!

This module performs conversions between Python values and C bit field structs represented as Python byte strings.

Project description



This module is intended to have a similar interface as the python struct module, but working on bits instead of primitive data types (char, int, …).



pip install bitstruct

Example usage

See the test suite:

A basic example of packing/unpacking four integers:

>>> from bitstruct import *
>>> pack('u1u3u4s16', 1, 2, 3, -4)
>>> unpack('u1u3u4s16', b'\xa3\xff\xfc')
(1, 2, 3, -4)
>>> calcsize('u1u3u4s16')

The unpacked fields can be named by assigning them to variables or by wrapping the result in a named tuple:

>>> from bitstruct import *
>>> from collections import namedtuple
>>> MyName = namedtuple('myname', [ 'a', 'b', 'c', 'd' ])
>>> unpacked = unpack('u1u3u4s16', b'\xa3\xff\xfc')
>>> myname = MyName(*unpacked)
>>> myname
myname(a=1, b=2, c=3, d=-4)
>>> myname.c

An example of packing/unpacking a unsinged integer, a signed integer, a float, a boolean, a byte string and a string:

>>> from bitstruct import *
>>> pack('u5s5f32b1r13t40', 1, -1, 3.75, True, b'\xff\xff', u'hello')
>>> unpack('u5s5f32b1r13t40', b'\x0f\xd0\x1c\x00\x00?\xffhello')
(1, -1, 3.75, True, b'\xff\xf8', u'hello')
>>> calcsize('u5s5f32b1r13t24')

The same format and values as in the previous example, but using LSB (Least Significant Bit) first instead of the default MSB (Most Significant Bit) first:

>>> from bitstruct import *
>>> pack('<u5s5f32b1r13', 1, -1, 3.75, True, b'\xff\xff')
>>> unpack('<u5s5f32b1r13', b'\x87\xc0\x00\x03\x80\xbf\xff')
(1, -1, 3.75, True, b'\xff\xf8')
>>> calcsize('<u5s5f32b1r13')

An example of unpacking values from a hexstring and a binary file:

>>> from bitstruct import *
>>> unpack('s17s13r24', '0123456789abcdef'.decode('hex'))
(582, -3751, b'\xe2j\xf3')
>>> with open("test.bin", "rb") as fin:
...     unpack('s17s13r24',
(582, -3751, b'\xe2j\xf3')

Change endianness of the data with byteswap(), and then unpack the values:

>>> from bitstruct import *
>>> packed = pack('u1u3u4s16', 1, 2, 3, 1)
>>> unpack('u1u3u4s16', byteswap('12', packed))
(1, 2, 3, 256)

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for bitstruct, version 3.3.1
Filename, size File type Python version Upload date Hashes
Filename, size bitstruct-3.3.1-py2.py3-none-any.whl (6.4 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size bitstruct-3.3.1.tar.gz (15.0 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page