Zero-fill shift

Scott David Daniels Scott.Daniels at Acm.Org
Wed May 5 14:26:16 EDT 2004


Daniel Orner wrote:

> In the Java algorithm, two integers are added. This often results in an 
> overflow and a negative number, which is the desired result. However, I 
> can't seem to duplicate that in Python...
(because addition in python works)
> I've tried various solutions, but haven't come up with something 
> that duplicates this behavior exactly.

> For reference, here's the Java code I'm trying to duplicate:
> 
> while(n-- > 0)
> {   sum += delta;
>     y += (z << 4)+a ^ z + sum ^ (z >>> 5) + b;
>     z += (y << 4)+c ^ y + sum ^ (y >>> 5) + d;
> }

How about:
POSITIVEMASK = int((1L << 31) - 1)
WORDSIGNBIT = 1L << 31

def signwrap(v):
     if v & WORDSIGNBIT:
         return int(v | ~POSITIVEMASK)
     return int(v & POSITIVEMASK)

for i in range(n):
     sum = signwrap(sum + delta)
     y = signwrap(y + (z << 4)+a ^ z + sum ^ (z >>> 5) + b)
     z = signwrap(z + (y << 4)+c ^ y + sum ^ (y >>> 5) + d)


-- 
-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list