32 bit arithmetic in 2.3+

Miki Tebeka mikit at zoran.co.il
Sun Oct 26 05:03:38 EST 2003


Hello Robin,

> I'm sure we've had this discussion before, but I'm getting a bunch of
> problems related to various algorithms related to 32 bit arithmetic.
> 
> The particular error/warnings I'm seeing are
> 
> FutureWarning: hex/oct constants > sys.maxint will return positive
> values in Python 2.4 and up
> 
> FutureWarning: x<<y losing bits or changing sign will return a long in
> Python 2.4 and up
> 
> related to the use of 0x81020304 and  << respectively.
> 
> Can someone tell me
> 
> 1) What feature makes these warnings errors?
Currently bitwise operation are on the system "native" types.
In 2.4 they will be a "logical" operation since ints and long ints
will be unified.
currently:
>>> 1<<64
__main__:1: FutureWarning: x<<y losing bits or changing sign will
return a long in Python 2.4 and up
0
>>> 1L<<64
18446744073709551616L
>>> 
In 2.4 and up 1<<64 will give the same result as 1L<<64

> 2) What's the right way to do the bit shifting modulo 32 bits?
> The same kinds of problems exist in java, but we don't get the warnings
> regarding the use of 0x80000000. Do I need to replace all 0x8........
> numbers with the L version and ensure all << shifts are masked with
> 0xffffffffL ? Surely there will be some compatibility issues.
IMO this is the best way. 
def lshift32(n):
    return (n << 32) & (0xFFFFFFFF)

HTH.
Miki




More information about the Python-list mailing list