How to make a Python Long from a long long in an extension

Warren Postma embed at NOSPAM.geocities.com
Mon Aug 28 13:31:12 EDT 2000


<searleir at my-deja.com> wrote in message news:8oe46r$gi6$1 at nnrp1.deja.com...
> I am writing an extension module that defines a new Python type.  This
> type is responsible for reading a stream of data, and creating a large
> table. Within the table is a column of time values that are 64 bits
> wide.  I can easily create the value properly using either GNUs long
> long, or MS __int64.
>
> The problem I am having is having is how do I get a 64 bit integer into
> a Python Long Integer.  PyLong_FromLong() takes a 32bit integer, not 64.
>  Casting to Double works, but truncates the precision for larger values.

I would have thought a PyLong_FromLong took a 64 bit value, given this
declaration:

PyObject * PyLong_FromLong(long ival);

But then I tried this in IDLE, and found that

A = 0xFFFFFFFF
print A
-1

That works fine, but this fails:

A = 0xFFFFFFFFF
OverflowError: integer literal too large.

So, then, this again, works:

A = 0xFFFFFFFFFFFFFFFFL

Then, because I hadn't tried this before I tried this:

print 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFL

1852673427797059126777135760139006525652319754650249024631321344126610074238
975L

As I had never tried this before, my initial reaction was "Holy mackerel!".
This is COOL.

So, here I see your options: Use PyLong_FromString after converting your 64
bit value into a string,
which should be easy enough, or for the more direct route, call
PyLong_FromLongLong if you have define HAVE_LONG_LONG.

Warren







More information about the Python-list mailing list