Zero-fill shift
Scott David Daniels
Scott.Daniels at Acm.Org
Sat Jun 26 11:58:44 EDT 2004
Eli Stevens (WG.c) wrote:
> Daniel Orner <cs993442 at cs.yorku.ca> wrote:
>
>>Great, this works. 8-) Unfortunately, I've run into another problem.
>>In the Java algorithm, two integers are added. This often results in
>>an overflow and a negative number, which is the desired result....
>
> But more to the point: Here's something that will do the trick if your
> overflow isn't ever more than one bit....
And if you want to be able to handle multibit overflow:
SIGN_BIT = 2 ** 7 # 31 if you prefer 32-bit signed numbers
def wrap(n):
if n & SIGN_BIT:
return n | -SIGN_BIT
else:
return n & (SIGN_BIT - 1)
--
-Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list