Integer arithmetic

Bengt Richter bokr at
Thu Mar 27 04:28:43 CET 2003

On Wed, 26 Mar 2003 12:38:25 GMT, Alex Martelli <aleax at> wrote:
>Daniel Timothy Bentley wrote:
>> Basically, if you're going to say ints and longs are separate types, I
>> think there should be a way to makes ints from longs fairly reliably.  I
>> don't think that's a niche, I think it's something a consistent language
>> should provice.
>Well, your proposed expression DOES "make ints from longs fairly reliably",
>it's just that I think the ints it makes are probably not the ones you'd
>like to get (except for 0<=foo<sys.maxint).
>I think you want something like: int(cmp(foo,0)*(abs(foo) & sys.maxint)).
>Me, I think it's better to incapsulate the "conversion to int ignoring
>overflow" in a function, using an if/else:
>def toint(foo):
>    if foo>=0: return int(foo&sys.maxint)
>    else: return -int(-foo&sys.maxint)
The above doesn't match typical hardware and C-style int behavior:

 >>> import sys
 >>> def toint(foo):
 ...     if foo>=0: return int(foo&sys.maxint)
 ...     else: return -int(-foo&sys.maxint)
 >>> hex(-sys.maxint-1)
 >>> -sys.maxint-1
 >>> type(-sys.maxint-1)
 <type 'int'>
 >>> toint(-sys.maxint-1)

Bug, ISTM.


Because two's complement "minint" is not -sys.maxint,
(it is -sys.maxint-1)

Bengt Richter

More information about the Python-list mailing list