Large integers from C

John Machin sjmachin at lexicon.net
Thu Feb 21 15:11:30 EST 2002


"Phil Mayers" <p.mayers at ic.ac.uk> wrote in message news:<20020221.144033.1012502954.7349 at ic.ac.uk>...
> In article <c76ff6fc.0202201519.509ec73e at posting.google.com>, "John
> Machin" <sjmachin at lexicon.net> wrote:
> 
> > Gustavo Niemeyer <niemeyer at conectiva.com> wrote in message
> > 
> > It is possible that the OP wants, but is not looking very hard for,
> > this:
> > 
> > [from Python 2.2 source, in include/longobject.h] """
> > /* _PyLong_FromByteArray:  View the n unsigned bytes as a binary integer
> > in
> >    base 256, and return a Python long with the same numeric value. If n
> >    is 0, the integer is 0.  Else:
> >    If little_endian is 1/true, bytes[n-1] is the MSB and bytes[0] the
> >    LSB; else (little_endian is 0/false) bytes[0] is the MSB and
> >    bytes[n-1] the LSB.
> >    If is_signed is 0/false, view the bytes as a non-negative integer. If
> >    is_signed is 1/true, view the bytes as a 2's-complement integer,
> >    non-negative if bit 0x80 of the MSB is clear, negative if set. Error
> >    returns:
> >    + Return NULL with the appropriate exception set if there's not
> >      enough memory to create the Python long.
> > */
> > extern DL_IMPORT(PyObject *) _PyLong_FromByteArray(
> >         const unsigned char* bytes, size_t n, int little_endian, int
> >         is_signed);
> > """
> 
> Ah, I should probably point out I am restricted to using Python 1.5.2 for
> various dull reasons, but in theory that is what I'm looking for.

So why not grab the source of _PyLong_FromByteArray() from the 2.2
distribution and put in your own code?

> However, I note that API isn't listed in the C API documentation.

So raise a doco enhancement request. Adequate comments in the .h file
of a module would be good enough for me.

> 
> I'll probably try the PyLong_FromString, and see if that helps.

Not sure how it could help, given your "in theory that is what I'm
looking for" above.
char string_513[] = "513";
char byte_array_513_little_endian[] = {1, 2};
"String" means external character representation. You would have to
convert your data to external format yourself.

BTW, how long are your own-format long numbers, what's the format, and
where are you getting them from in the first place?



More information about the Python-list mailing list