You may find the bitstring module useful if you have more complex needs than string formatting can be.
>>> from bitstring import BitArray
>>> a = BitArray(24)
>>> a.uint = 2**24/11
>>> a.bin
'000101110100010111010001'
It never truncates the initial zero bits and can do some more useful tricks.
>>> a.uint /= 2
>>> a.bin
'000010111010001011101000'
>>> list(a.findall('0b1011'))
[4, 14]
>>> a *= 2
>>> a.bin
'000010111010001011101000000010111010001011101000'
>>> a.replace('0b00001', '0xe')
2
>>> a.bin
'1110011101000101110100011100111010001011101000'
I'm not sure about your specific needs, so all this can be excessive, and you can not use an external library in any case, but the built-in Python support for bit arrays is a bit basic.
source
share