Skip to content

More efficient conversion from Python int to fmpz #159

Description

@oscarbenjamin

It looks like Python 3.13 will provide public C API for efficiently converting to and from a PyLong. These should be compatible with mpz_import/mpz_export rather than converting between hex strings:

python/cpython#121339

cdef inline int fmpz_set_pylong(fmpz_t x, obj):
cdef int overflow
cdef slong longval
longval = pylong_as_slong(<PyObject*>obj, &overflow)
if overflow:
s = "%x" % obj
fmpz_set_str(x, chars_from_str(s), 16)
else:
fmpz_set_si(x, longval)

cdef fmpz_get_intlong(fmpz_t x):
"""
Convert fmpz_t to a Python int or long.
"""
cdef char * s
if COEFF_IS_MPZ(x[0]):
s = fmpz_get_str(NULL, 16, x)
v = int(str_from_chars(s), 16)
libc.stdlib.free(s)
return v
else:
return <slong>x[0]

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions