Integer arithmetic

Alex Martelli aleax at aleax.it
Tue Mar 25 04:29:07 EST 2003


Daniel Timothy Bentley wrote:

> I am currently embarking on the utterly futile and mildly recursive task
> of implementing a C interpreter in python (Jython specifically).
> 
> Right now, I'm trying to think about integer ops.
> 
> I want to add two integers, e.g., and have the result be an integer.  The

And what do you want to happen when the two integers you're adding yield
a result too large to be represented as an integer?  You do no specify
what behavior you want for that (and I believe the C standard doesn't,
either, though I'm not familiar with the 1999 version, only the older one).

Basically what you need is a function makeint that will return the int
of its single argument -- if that overflows, then you may want to e.g.
truncate that to 32 bits, or whatever.  Since most cases won't overflow
you're best off with an "easier to ask forgiveness than permission"
structure, e.g.:

def mask(x, themask = 0x7FFFFFFF):
    return int(x & themask)

def makeint(x):
    try: return int(x)
    except OverflowError:
        if x < 0:
            return -mask(-x)
        else:
            return mask(x)

> naive way:
> 
> foo = bar + baz
> 
> Doesn't work because of automatic promotion to bignum.

so you code

    foo = makeint(bar + baz)

with some makeint function such as the above one.


Alex





More information about the Python-list mailing list