struct.pack and perl's 'B' code for bitstrings

Oren Tirosh oren-py-l at hishome.net
Sat Jun 28 04:49:46 EDT 2003


On Fri, Jun 27, 2003 at 02:19:35PM -0600, Justin Johnson wrote:
> Is there anything equivalent to perl's pack code B, which allows you to
> specify bits to pack?  For example, in perl, pack('B8', '00000010') will
> return 8 bits exactly as the bit string appears.  I don't see any similar
> codes in struct.pack.  In general struct.pack is not as robust as perl's
> pack function.  

Are you using the word 'robust' to mean 'featureful'?  

> Is there a better version of struct somewhere, or how are
> people overcoming some of these problems?

I've heard of some alternative version of struct. I've never checked if 
they have bitstring options. When I need something like this I just use 
the int or long constructor with radix 2:

>>> struct.pack('B', int('00000010', 2))
'\x02'

>>> struct.pack('>H', int('0001001000011000', 2))
'\x12\x18'

    Oren





More information about the Python-list mailing list