integer type conversion problem/question

Faheem Mitha faheem at email.unc.edu
Sat Oct 9 08:50:20 CEST 2004


Hi,

I'm not sure what would be more appropriate, so I'm ccing it to both
alt.comp.lang.learn.c-c++ and comp.lang.python, with followup to
alt.comp.lang.learn.c-c++.

While working with a random number generator in the context of a mixed
Python/C++ programming problem. I encountered a vexing type
conversion problem.

Briefly, the situation is as follows.

I have a integer in Python (Python integers are implemented as C long
ints).

This is passed to a function in C++ which converts it (supposedly) to
an unsigned int, modifies it and then passes it back to Python. This
is done since the random number generator uses unsigned ints.

Python attempts to convert it to a Python integer, and if it is too
large, converts it into a Python long. (Both integer and long are
Python types).

Now, my program crashes, because at some point the unsigned integer
passed to Python becomes too long to be represented as an (unsigned)
int, and I get an overflow error.

OverflowError: long int too large to convert to int

An example of such a number is 2321871520. Python thinks this should
be a long, but my C++ code seems to handle it as an unsigned int, and
passes it to Python as such. When Python converts it to a long and
tries to pass it back, I get a runtime error.

Python gives:

In [1]: 2321871520
Out[1]: 2321871520L


I tried compiling the following fragment of code (header ommitted) and
got a compiler warning:  warning: this decimal constant is unsigned
only in ISO C90.

I'm not sure what to make of this.

*******************************
int main()
{
  unsigned int a = 2321871520;
  cout << a << endl;
  return 0;
}
*********************************

I find all this a little strange. Since in theory Python ints are
larger than C ints (since Python ints are implemented as C long ints),
there should be (in theory) no problem converting C unsigned ints to
Python integers (corresponding to C long integers) but in practice
there is. Can anyone enlighten me as to this puzzling situation?
Thanks.

I'd be happy to give more details as necessary. I realise the above
may not be entirely clear, but excessive detail may be confusing.
Please CC me on any reply. Thanks.

                                                          Faheem.



More information about the Python-list mailing list