"Robert Berman" <berma...@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/

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to