[Tutor] Bits operations

Jeff Shannon jeff@ccvcorp.com
Thu Jul 10 19:26:01 2003


Guillermo Fernandez wrote:

> 1- How much bits does an integer take? I would like to play with 32 
> bits words and I don't really know how to limit this and specially fix 
> the size in python (they say an int is represented by a long with _at 
> least_ 32 bits...). 


A Python integer, IIRC, uses whatever the given platform's C long is. 
 For most systems (i.e., 32bit platforms), this is 32 bits.  (Note that 
for most 32-bit platforms, C compilers use the same size for a long and 
an int ...)  However, on 64-bit platforms this would probably be 64 bits.

> 2- I've not seen any binary representation of integers (thus there 
> exist octal and hexa...). It's easier to see something like 
> 00101001B... does it exist? 


There isn't a built-in function to do this, but it's not too difficult 
to write one.  (You can find several examples in the archives of this 
list.)  However, you may be better off using hex -- with a little bit of 
practice, it's not too hard to recognize each hex digit as a pattern of 
four bits.

> 3- I've seen some bit-sting operations. Is there an easy way of 
> reading the value of a bit in python in a straightforward manner? (for 
> example "the bit i of integer n has a value 1 or 0?"). 


The best way to do this is to bitwise-AND your unknown byte with a known 
constant.

if myvar & 0x01:
    # the first (least significant) bit is set
if myvar & 0x04:
    # the third-least significant bit is set
if myvar & 0x80:
    # the 8th (i.e. most significant) bit is set

Note that any byte can be uniquely represented with two hex digits, and 
it doesn't take long before you can see that 0x0C (12) is equivalent to 
binary 0000 1100.

Jeff Shannon
Technician/Programmer
Credit International