• Stars
    star
    120
  • Rank 295,983 (Top 6 %)
  • Language
    C
  • License
    MIT License
  • Created over 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python bit pack/unpack package.

About

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, ...).

Project homepage: https://github.com/eerimoq/bitstruct

Documentation: https://bitstruct.readthedocs.io

Installation

pip install bitstruct

Performance

Parts of this package has been re-implemented in C for faster pack and unpack operations. There are two independent C implementations; bitstruct.c, which is part of this package, and the standalone package cbitstruct. These implementations are only available in CPython 3, and must be explicitly imported. By default the pure Python implementation is used.

To use bitstruct.c, do import bitstruct.c as bitstruct.

To use cbitstruct, do import cbitstruct as bitstruct.

bitstruct.c has a few limitations compared to the pure Python implementation:

  • Integers and booleans must be 64 bits or less.
  • Text and raw must be a multiple of 8 bits.
  • Bit endianness and byte order are not yet supported.
  • byteswap() can only swap 1, 2, 4 and 8 bytes.

See cbitstruct for its limitations.

MicroPython

The C implementation has been ported to MicroPython. See bitstruct-micropython for more details.

Example usage

A basic example of packing and unpacking four integers using the format string 'u1u3u4s16':

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

An example compiling the format string once, and use it to pack and unpack data:

>>> import bitstruct
>>> cf = bitstruct.compile('u1u3u4s16')
>>> cf.pack(1, 2, 3, -4)
b'\xa3\xff\xfc'
>>> cf.unpack(b'\xa3\xff\xfc')
(1, 2, 3, -4)

Use the pack into and unpack from functions to pack/unpack values at a bit offset into the data, in this example the bit offset is 5:

>>> from bitstruct import *
>>> data = bytearray(b'\x00\x00\x00\x00')
>>> pack_into('u1u3u4s16', data, 5, 1, 2, 3, -4)
>>> data
bytearray(b'\x05\x1f\xff\xe0')
>>> unpack_from('u1u3u4s16', data, 5)
(1, 2, 3, -4)

The unpacked values 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
3

Use the pack_dict and unpack_dict functions to pack/unpack values in dictionaries:

>>> from bitstruct import *
>>> names = ['a', 'b', 'c', 'd']
>>> pack_dict('u1u3u4s16', names, {'a': 1, 'b': 2, 'c': 3, 'd': -4})
b'\xa3\xff\xfc'
>>> unpack_dict('u1u3u4s16', names, b'\xa3\xff\xfc')
{'a': 1, 'b': 2, 'c': 3, 'd': -4}

An example of packing and unpacking an unsigned 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', 'hello')
b'\x0f\xd0\x1c\x00\x00?\xffhello'
>>> unpack('u5s5f32b1r13t40', b'\x0f\xd0\x1c\x00\x00?\xffhello')
(1, -1, 3.75, True, b'\xff\xf8', 'hello')
>>> calcsize('u5s5f32b1r13t40')
96

The same format string 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('<u5s5f32b1r13t40', 1, -1, 3.75, True, b'\xff\xff', 'hello')
b'\x87\xc0\x00\x03\x80\xbf\xff\xf666\xa6\x16'
>>> unpack('<u5s5f32b1r13t40', b'\x87\xc0\x00\x03\x80\xbf\xff\xf666\xa6\x16')
(1, -1, 3.75, True, b'\xff\xf8', 'hello')
>>> calcsize('<u5s5f32b1r13t40')
96

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

>>> from bitstruct import *
>>> from binascii import unhexlify
>>> unpack('s17s13r24', unhexlify('0123456789abcdef'))
(582, -3751, b'\xe2j\xf3')
>>> with open("test.bin", "rb") as fin:
...     unpack('s17s13r24', fin.read(8))
...
...
(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)

A basic example of packing and unpacking four integers using the format string 'u1u3u4s16' using the C implementation:

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

Contributing

  1. Fork the repository.

  2. Install prerequisites.

    pip install -r requirements.txt
    
  3. Implement the new feature or bug fix.

  4. Implement test case(s) to ensure that future changes do not break legacy.

  5. Run the tests.

    make test
    
  6. Create a pull request.

More Repositories

1

gqt

Build and execute GraphQL queries in the terminal.
Python
461
star
2

simba

Simba Embedded Programming Platform.
C
339
star
3

monolinux

Create embedded Linux systems with a single statically linked executable.
Makefile
324
star
4

asn1tools

ASN.1 parsing, encoding and decoding.
Python
290
star
5

detools

Binary delta encoding tools.
Python
159
star
6

monolinux-jiffy

A Monolinux distro for the Jiffy board!
C
154
star
7

moblin

Moblin, a free iOS app for IRL streaming.
Swift
133
star
8

bincopy

Mangling of various file formats that conveys binary information (Motorola S-Record, Intel HEX, TI-TXT, Verilog VMEM, ELF and binary files).
Python
102
star
9

dbg-macro

A set of dbg(…) macros for C
C
79
star
10

pbtools

Google Protocol Buffers tools (C code generator).
C
72
star
11

nala

🦁 Nala - A delightful test framework for C projects.
C
69
star
12

pumbaa

Python on Simba.
C
62
star
13

mqttools

MQTT version 5.0 client and broker using asyncio
Python
61
star
14

hardware-reference

Various documents.
55
star
15

textparser

A text parser.
Python
29
star
16

async

🔀 Asynchronous framework in C.
C
26
star
17

pyfuzzer

Fuzz test Python modules with libFuzzer
Python
24
star
18

asyncudp

Asyncio high level UDP sockets.
Python
24
star
19

asyncbg

Asyncio background tasks
Python
16
star
20

monolinux-raspberry-pi-3

A Monolinux distro for Raspberry Pi 3!
C
15
star
21

bitstream

A bit stream library for C.
C
15
star
22

messi

⚽ Reliable message passing in distributed systems.
C
14
star
23

pictools

Microchip PIC tools for software developers.
C
13
star
24

ecdtools

Electronic circuit design tools.
Python
10
star
25

monolinux-c-library

The Monolinux C library.
C
9
star
26

traceback

Colorful stack traceback in C on Linux.
C
9
star
27

soundid

Sound identification.
Python
7
star
28

humanfriendly

Human friendly C library.
C
7
star
29

monolinux-example-project

A Monolinux example project.
C
6
star
30

irwin

Plotting data in the terminal
Python
5
star
31

expect

Programmed dialogue with interactive streams.
Python
5
star
32

bunga

Control and monitor your system.
C
5
star
33

advent-of-code

https://adventofcode.com/
Python
4
star
34

systest

System test framework.
Python
4
star
35

simba-esp32

ESP32 for Simba
C
4
star
36

moblin-remote-control-relay

Moblin Remote Control Relay
JavaScript
4
star
37

argparse_addons

Additional Python argparse types and actions.
Python
3
star
38

terminal_graphics

Who knows?!?
Python
3
star
39

uml

Unified Modeling Language (UML)
Python
2
star
40

obs-remote-control-relay

OBS Remote Control Relay
JavaScript
2
star
41

romeo

C
2
star
42

drmario

Dr. Mario OBS plugin.
CMake
2
star
43

httpasync

HTTP Async
Python
2
star
44

avr-toolchain-windows

AVR toolchain for Windows
C
2
star
45

rafiki

Rust on Simba.
Rust
2
star
46

moblin_assistant

Moblin remote control assistant.
Python
2
star
47

Rist

librist Swift wrapper
Swift
1
star
48

monolinux-rust-jiffy

Monolinux in Rust for the Jiffy board
Dockerfile
1
star