FAQ
Am I so far off in thinking maybe this should be provided by the language?
Some way to create an int, using some (perhaps implementation-defined)
method of changing a long to an int? Some way to ensure that I don't
misguess on what themask is? What if I'm programming on a machine with 36
bit longs? Or where 64 bits is the atomic datatype?
It seems like there should be an int constructor that won't overflow in
this case.

Unless there's a function I'm missing that returns INT_MAX (as C
pronounces it) and I'm just supposed to mod it.

-Dan
On Tue, 25 Mar 2003, Alex Martelli wrote:

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

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

People

Translate

site design / logo © 2022 Grokbase