Search code examples
cgmp

mpz_t to unsigned long long conversion (gmp lib)


Is there a way to convert a mpz_t variable to unsigned long long in C?How about the other way around,from ull to mpz_t?The gmp library doesn't support this as ull are part of C99. I found this but it's in c++,and I don't know how to code in c++.Thanks in advance.


Solution

  • Here are some functions for translating between unsigned long long and mpz_t. Note that mpz2ull will smash your stack if the number is too big to fit into an unsigned long long:

    unsigned long long mpz2ull(mpz_t z)
    {
        unsigned long long result = 0;
        mpz_export(&result, 0, -1, sizeof result, 0, 0, z);
        return result;
    }
    
    void ull2mpz(mpz_t z, unsigned long long ull)
    {
        mpz_import(z, 1, -1, sizeof ull, 0, 0, &ull);
    }