Zero-fill shift

Diez B. Roggisch deetsNOSPAM at web.de
Tue May 4 16:24:21 EDT 2004


Daniel Orner wrote:

> I'm trying to port a (relatively) simple encryption algorithm from Java
> code (mainly because the algorithm will be used identically in both
> contexts). However, the code makes extensive use of Java's >>> operator,
> which shifts right and fills in the leftmost bits with zeroes. I've been
> unable to duplicate that effect in Python.
> Apparently, a >>> b is equal to the following:
> 
>     if a >= 0: return a >> b
>     else: return (a>>b)+(2<<~b)
> 
> However, Python complains when I try to do the left-shift, because ~b
> is often a negative number. Does anyone have a better idea about how I
> should go about doing this?

from what I can see from the java and python docs, all you should need is a
mask for the upper bits.

masks = [0xffffffff] + [0x7fffffff >> i for i in xrange(31)]

then your op is:

(a >> b) & masks[b]


-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list