Integer Overflow

Gareth McCaughan Gareth.McCaughan at pobox.com
Tue Nov 27 23:21:03 CET 2001


"Ursus Horibilis" wrote:

> Thanks very much.  I did not realize that a Python long was not
> simply a 64-bit number.  Just pure ignorance on my part.  Is it
> legal to mask a long and assign it to an int?  For example:
> 
> (a) is an (int), (b) is a (long)
> 
> b = 6*sys.maxint
> 
> a = b & (0xFFFFFFFF)

Yes, but the fact that you ask the question indicates that
your model of the universe isn't quite the same as Python's.
In Python, unlike C, *values* have types but *variables*
don't. There's no such thing as a variable that can only
hold "int"s in Python, for instance. So there's nothing
illegal about the following (stupid) code fragment:

    x = 123                 # now x contains a short integer
    x = "I am the walrus"   # now x contains a string
    x = 123L**100           # now x contains a long integer
    x = None                # now x contains None
    x = [1,2,3,4,5]         # now x contains a list
    x = (1,2,3)             # now x contains a tuple
    class X: pass           # (preparing for next line)
    x = X()                 # now x contains a class instance
    x = X                   # now x contains a class object
    x = {1:"a", 2:-1}       # now x contains a dictionary

The same variable can hold all these different types of
object: the type information lives with the object, the
value, not with the variable. The nearest C equivalent
(which isn't very near) would be having all your variables
be "void *" pointers, and having enough information in
the things pointed to to reconstruct everything. If you
do Visual Basic then you might like to think in terms of
the Variant type. But it's healthier to think of it on
its own terms, rather than mentally trying to translate
to C, or Java, or Forth, or whatever.

Oh, by the way: sys.maxint is a short integer, not a
long integer (NB that when I say "short" here I mean
"the same length as a C long on your platform"!), so
evaluating 6*sys.maxint will produce an exception. You
could say "6L*sys.maxint", though.

-- 
Gareth McCaughan  Gareth.McCaughan at pobox.com
.sig under construc



More information about the Python-list mailing list