Efficient Bit addressing in Python.

Tino Wildenhain tino at wildenhain.de
Thu Oct 9 13:49:34 CEST 2008


Hendrik van Rooyen wrote:
> Is there a canonical way to address the bits in a structure
> like an array or string or struct?
> Or alternatively, is there a good way to combine eight
> ints that represent bits into one of the bytes in some
> array or string or whatever?
> It seems to me that there is a dilemma here :
> if you can write:
> bit3 = 1
> Then you have to jump through hoops to get
> bit0 through bit7 into some byte that you can send
> to an i/o routine.
> On the other hand, if you keep the bits "in" the 
> byte, then you can write:
> byte[3] = '\x7e'
> but you have to jump through hoops to get at 
> the individual bits.
> Is there a "best" way?
> It would be nice to be able to write:
> if io.byte2.bit3:
>    do_something()
> if io.byte2 == alarm_value:
>   do_something_else()
> where:
>  io.byte2 & 8   "is"  io.byte2.bit3

byte1 byte2? this does not look very practical
to me. In the simplest form of storing
your values in a text string, you could just
use ord() to get the byte value and
operate on it with 1<<0 1<<1 1<<3 and so on.

If you want, put a module in which defines the


and so on and use it via
if byte & bit1: ...

more efficiently for operations on really big
bit strings is probably just using integers.


> Is this possible?
> - Hendrik
> --
> http://mail.python.org/mailman/listinfo/python-list

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20081009/a9ceb113/attachment.bin>

More information about the Python-list mailing list