Is there a nicer way to pass python long ints (bigint) into C efficiently? I'm currently cutting the value up into 64 bit chunks in python and passing in as an unsigned long*: cdef("int bigInt(int n, unsigned long* x);") x = sum(1 << i for i in [100,200,123]) xs = [] while x > 0: xs.append(x & ((1 << 64) - 1)) x >>= 64 print lib.bigInt(len(xs), xs) but this is quite slow, and it seems like this data must already be lurking somewhere in exactly the right form. njh
2013/11/8 Nathan Hurst <njh@njhurst.com>
Is there a nicer way to pass python long ints (bigint) into C efficiently? I'm currently cutting the value up into 64 bit chunks in python and passing in as an unsigned long*:
cdef("int bigInt(int n, unsigned long* x);")
x = sum(1 << i for i in [100,200,123]) xs = [] while x > 0: xs.append(x & ((1 << 64) - 1)) x >>= 64 print lib.bigInt(len(xs), xs)
but this is quite slow, and it seems like this data must already be lurking somewhere in exactly the right form.
In Python3 you could use the to_bytes() method of ints, but I could not find any way to have the same in python2. Or just use hex(). You might have endianness issues, though. -- Amaury Forgeot d'Arc
Hi Nathan, On Fri, Nov 8, 2013 at 4:35 PM, Amaury Forgeot d'Arc <amauryfa@gmail.com> wrote:
Is there a nicer way to pass python long ints (bigint) into C efficiently?
It depends what the C code wants to do with it. If it's just for passing around, you can use ffi.from_handle(). If the C code expects to read the value, then I fear you need to decompose it into some format, either manually or using hex() or marshal. The internal format of longs in PyPy is not directly accessible: it is not using 64-bit integers, but 63-bit if the C compiler supports __int128_t and 31-bit otherwise. A bientôt, Armin.
participants (3)
-
Amaury Forgeot d'Arc
-
Armin Rigo
-
Nathan Hurst