# [Tutor] working with bit arrays

Alan Gauld alan.gauld at btinternet.com
Thu Dec 3 01:53:02 CET 2009

```"Robert Berman" <bermanrl at cfl.rr.com> wrote

> I am trying to represent a number as a list of bits: for example the bit
> representation of the integer 8.

Numbers are already represented as arrays of bits, thats how
they are stored.

> 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.

You can do that using bitmasks. For example to extract the 4th bit
use

bit4 = value & 0x08    # 0x08 = 00001000

For bit 2 use

bit2 = value & 0x02   # 0x02 = 00000010

You can iterate over each bit using

for index in range(number_of_bits):
print "bit", index + 1, "is", int(bool(value & (2**index)))    #
int(bool()) prints 1/0

Or am I missing something?

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

```