Bitstring is a pure Python module designed to help make the creation and analysis of binary data as simple and natural as possible. The documentation is really good and this page limits itself to some quick examples.
In [1]:
import bitstring
In [2]:
from_hex = bitstring.BitArray('0x0001b3')
from_bin = bitstring.BitArray('0b001100')
from_oct = bitstring.BitArray('0o34100')
from_int = bitstring.BitArray(uint=45, length=8)
from_int_bigendian = bitstring.BitArray(intbe=-32768, length=16)
from_float = bitstring.BitArray(float=10.3, length=32) # floats must be 32 or 64 bits long
from_float_littleendian = bitstring.BitArray(floatle=-273.15, length=64) # floats must be 32 or 64 bits long
from_raw = bitstring.BitArray(bytes=b'\x00\x01\x02\xff', length=28)
from_bool = bitstring.BitArray(True)
In [3]:
from_hex, from_bin, from_oct, from_int, from_int_bigendian, from_float, from_float_littleendian, from_raw, from_bool
Out[3]:
In [4]:
from_int.bin, from_int.bytes, from_int.uint, from_int.int, from_int.hex, from_float_littleendian.floatbe
Out[4]:
In [5]:
len(from_bool), len(from_float)
Out[5]:
In [6]:
from_int[-4:].bin, from_int[:4].int
Out[6]:
In [7]:
from_hex + from_int
Out[7]:
In [16]:
seven_bits = bitstring.BitArray(int=32, length=7)
len(seven_bits), seven_bits.bin
Out[16]:
In [18]:
seven_bits.tobytes() # tobytes() ensures padding to byte-alignment
Out[18]:
In [10]:
packed = bitstring.pack('bool, int:7, floatbe:32', True, -32, -273.15)
len(packed), packed.bin, packed.bytes
Out[10]:
In [11]:
packed.unpack('bool, int:7, floatbe:32')
Out[11]:
In [12]:
list(packed.find('0b0000')), list(packed.findall('0b0000'))
Out[12]:
In [13]:
packed.replace('0b0000', '0b1111')
packed.bin
Out[13]:
In [14]:
packed.startswith('0b111'), packed.endswith('0b111')
Out[14]:
In [15]:
a = bitstring.BitArray('0b00001111')
b = bitstring.BitArray('0b01010101')
(a).bin, (~a).bin, (a<<2).bin, (a>>2).bin, (a*2).bin, (a&b).bin, (a|b).bin, (a^b).bin
Out[15]:
In [ ]: