Getting at the bits of a 32-bit integer
Paul Rubin
http
Mon Aug 23 20:16:31 EDT 2004
jacobsmail at postmark.net (Jacob H) writes:
> 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...
It's not really in the Python spirit, but in general you can set the
nth bit (from the right, starting at n=0) of variable x by saying:
x |= (1 << n)
You can clear it with
x &= ~(1 << n)
and you can test it with
if x & (1 << n):
do whatever
More information about the Python-list
mailing list