Getting at the bits of a 32-bit integer

Phil Frost indigo at bitglue.com
Mon Aug 23 20:15:08 EDT 2004


If you really want to do that, you can use the bitwise "and" and "or"
operators to unset/set bits, respectivly. For example, if you want to
set bit 9, that's 0x0100, or 0000 0001 0000 0000 in binary. The integer
'i' with bit 9 unset is 'i & ~0x0100' (~ is the one's complement or
bitwise not operator; it inverts all the bits), and 'i | 0x0100' is 'i'
with bit 9 set. You can also use the bitwise exclusive or "^" to toggle
a bit, like 'i ^ 0x0100'.

However, doing this sort of thing is rather nonpythonic. Python
abstracts the platform's representation of an integer. Integers in
Python arn't always 32 bits; they are actually the size of C's 'long'
type, which is to say you can find the size by looking at sys.maxint,
but it's more trouble than it's worth. You will also encounter problems
if you change the highest bit:

>>> 10 ^ (1 << 31)
__main__:1: FutureWarning: x<<y losing bits or changing sign will return
a long in Python 2.4 and up
-2147483638

Note that the error message isn't even accurate. This is probably a good
indication that this isn't a common use case!

So, short story: use a bool (True/False)

On Mon, Aug 23, 2004 at 04:52:07PM -0700, Jacob H wrote:
> Hi there list,
> 
> I'm a beginning programmer, so please correct me if any of the
> following assumptions are wrong.
> 
> Suppose I have the decimal number 255. Since integers in Python are 32
> bits, it would look like this in binary:
> 
> 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...
> 
> Thanks in advance for any help on this. :)



More information about the Python-list mailing list