[Tutor] Bits operations

Alan Gauld alan.gauld@blueyonder.co.uk
Fri Jul 11 03:48:01 2003


> 1- How much bits does an integer take? I would like to play with 32
bits

Most machines nowadays use 32 bits/integer but as 64 bit machines
come on stream that will change(eg the new G5 Mac).

> 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?

Discussed here many times, search the archives :-)

> 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?").

Try creating a dictionary of bit masks:

bits = {0:1,1:2,2:4,3:8,...,31:0x8000}

then you can extract the nth bit by

bit = val & bits[n]

Or alternatively write a function that returns 2**n to get the mask:

def mask(n): return 2**n

bit = val & mask(n)

HTH,

Alan G.