Getting at the bits of a 32-bit integer

Jeremy Bowers jerf at
Tue Aug 24 02:16:46 CEST 2004

On Mon, 23 Aug 2004 16:52:07 -0700, Jacob H wrote:
> 00000000 00000000 00000000 11111111
> There are plenty of unused bits to the left of the number itself. If I
> wanted to use some of these bits as true/false flags, how would I go about
> it? In Python, how do I write code that gets at the leftmost byte, or the
> third bit from the left of the set of 32, or the rightmost byte plus the
> bit to its left, etc...

Well, the basic answer is the same as C, with &, >>, and appropriate
constants for what you are doing.

>>> #access the 10th bit
>>> a = 1025
>>> (a & 1024) >> 10
>>> a = 1023
>>> (a & 1024) >> 10

Obviously, you need better constants and stuff.

However, I must challenge your need to do this in the first place.
Python and bit twiddling generally don't go together; even if you are
accessing a binary file or protocol you should shuffle out as much to the
struct (?) module as possible. If you want to track every bit and byte,
Python is the wrong language for you... and unless you are tracking many
many millions of bits, this is the wrong decade for it.

Use a class, and set members on it to true or false for your flags. 

>>> class DummyStruct: pass
>>> flags = DummyStruct()
>>> flags.aFlag = True

(The nice thing about such classes is you will often find them smoothly
transition into really *useful* classes, emphasis on the plural "classes" :-).)

The bit twiddling will most likely be *much* slower than this, and unless
you're dealing with millions of these, the memory savings will be zilch.

If you *are* dealing with millions of these, be sure to look at the
"array" module.

More information about the Python-list mailing list