[Tutor] working with bit arrays

Wayne Werner waynejwerner at gmail.com
Wed Dec 2 19:48:00 CET 2009


On Wed, Dec 2, 2009 at 12:08 PM, Robert Berman <bermanrl at cfl.rr.com> wrote:

>  Hi,
>
> I am trying to represent a number as a list of bits: for example the bit
> representation of the integer 8. I did find a number of articles pertaining
> to a module called bitarray but I was unable to download/install that
> package. I am using Linux on Ubuntu 9.10; Python 2.6.2.
>
> I am almost certain there is a relatively easy way to convert an integer
> that can be represented by 32 bits into an array of bits that I can iterate
> over looking for switched on bits or switched off bits.
>
> Any information such as recipes or past articles in this list providing
> methods to create and manipulate  bit arrays would be most appreciated.
>

Python 2.6+ (as far as I know) has the bin() function:

Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)]
on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> bin(8)
'0b1000'
>>>

And larger:

>>> bin(99999999999999999999999)
'0b10101001011010000001011000111111000010100101011110110011111111111111111111111'

You can convert them to integers to use ^ (XOR) or & (AND) and other binary
operations on them:
http://docs.python.org/reference/expressions.html#binary-bitwise-operations

>>> a = int('01001', 2)
>>> b = int('00001', 2)
>>> a & b == b
True
>>> a = int('01110', 2)
>>> a & b == b
False

There may be some other way to check, but that's probably the easiest I know
of.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091202/a7577bd1/attachment.htm>


More information about the Tutor mailing list