integer type conversion problem/question

Faheem Mitha faheem at email.unc.edu
Sat Oct 9 15:51:34 EDT 2004


On Sat, 09 Oct 2004 19:36:13 GMT, Faheem Mitha <faheem at email.unc.edu> wrote:
> On Sat, 09 Oct 2004 19:31:30 GMT, Faheem Mitha <faheem at email.unc.edu> wrote:
>
>
>> I did have one followup question. If Python implements its integers as
>> signed C ints then surely 2^31 - 1 should be an integer rather than a
>> long? But I get
>>
>>  In [9]: 2**31 - 1
>>  Out[9]: 2147483647L
>>
>>  In [10]: type(2**31 - 1)
>>  Out[10]: <type 'long'>
>
> Belated followup to my own message. The following behaves as expected.
>
> In [13]: 2147483647
> Out[13]: 2147483647
>
> In [14]: 2147483648
> Out[14]: 2147483648L
>
> Apparently there is something about the ** notation that makes Python
> think of this as a long. Since Python people are more likely to know
> the answer, I'm ccing comp.lang.python despite the followup. Thanks.

Eric Brewer kindly replied (directly to me), so I'm copying it here.

********************************************************************
This is because 2**31 is a long (and *then* you subtract 1)

>>> 2**31-1
2147483647L
>>> 2**30
1073741824
>>> 2**30 + 2**30
2147483648L

Here is one way to get 2**31-1 as a regular int:

>>> 2**30 + (2**30-1)
2147483647
**********************************************************************

                                                         Faheem.



More information about the Python-list mailing list