[Tutor] Bits operations

Magnus Lyckå magnus@thinkware.se
Thu Jul 10 19:32:02 2003


At 00:09 2003-07-11 +0200, Guillermo Fernandez wrote:
>Cheers,
>
>I'm playing with crypto algorithms (I just get out of the exam and I'm 
>kind of masochist ;-) and there's of course bit operations.

I guess you'll get what you deserve! ;)

>Here's my problems:
>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...).

32 bits today, but I'd like to raise a warning here! While
0xffffffff means -1 in Python version < 2.3, it's like below
in 2.3:

 >>> 0xffffffff
<stdin>:1: FutureWarning: hex/oct constants > sys.maxint will return 
positive values in Python 2.4 and up
-1

This is because of the ongoing unifiction between the
integer and long types.

Maybe you should use pyrex? That will let you use C types,
and get much faster code than normal Python code.

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

Nope. I pestered Guido about that in Charleroi during
EuroPython, and he was determined there was no practical
use for it. If you really want it, pester him on Python-dev! :)

I think it would be good for learning about computers, but
he doesn't seem to be very keen on ones and zeroes...

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

Write a function?

def bits(x):
     i = 0
     while x:
         print "%i: %i" % (i, x%2)
         x = x >> 1
         i += 1

If you just wonder about a particular bit, just do

 >>> def set_bit(n, i):
...     return (n & (1<<i)) != 0
...
 >>> set_bit(127,6)
True
 >>> set_bit(127,7)
False


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language