Integer arithmetic

Daniel Timothy Bentley dbentley at stanford.edu
Tue Mar 25 01:18:27 EST 2003


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
naive way:

foo = bar + baz

Doesn't work because of automatic promotion to bignum.

foo = int(bar + baz)

seems not to work because of OverflowError, and catching it seems to do
little, as the error has already occured.  I'm sure there are hacks I
could do, but if I want an implementation that will act the way c int's
(or long's, or some appropriately sized type) do, is there an elegant way
of creating such a function?

Extra points for hit about keeping signed v. unsigned information correct.

Of course, I could always make a hacked-up version, but it seems like this
should be something I can pass-through.

Thanks in advance,
D"newbie"an





More information about the Python-list mailing list