Efficient Bit addressing in Python.
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 = '\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:
> if io.byte2 == alarm_value:
> 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
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
More information about the Python-list