Convert ull to mpz_t

I saw a message to mpz_t for unsigned long conversion (gmp lib) and Chris Shut-Jung gave me the answer

mpz_t ull2mpz(unsigned long long ull)
{
    char buf[40];
    int len;
    mpz_t result;

    len = snprintf(buf, sizeof buf, "%llx");
    if (len >= sizeof buf) { /* oops */ }
    mpz_init(result);
    len = gmp_sscanf(buf, "%Zx", result);
    if (len != 1) { /* oops */ }
    return result;
}

The problem is that, as stated in How to convert the GMP C parameter convention to something more natural? mpz_t is an array. How can I get around this (without doing weird things, just returning a value)? If I write instead

void mpz_set_ull(mpz_t val, unsigned long long ull){
    char buf[40];
    int len;
    mpz_t result;

    len = snprintf(buf, sizeof buf, "%llx");
    if (len >= sizeof buf) { /* oops */ }
    mpz_init(result);
    len = gmp_sscanf(buf, "%Zx", result);
    if (len != 1) { /* oops */ }
    mpz_set(val,result);
}

I get the wrong results.

And, is its code legal C?

0
source share
1 answer

OP does not use snprintf()correctly. Must pass ull.

Using

char buf[sizeof(ull)*CHAR_BIT/3 + 2];  // let the sizeof `buf` be sized per `ull` needs
...
snprintf(buf, sizeof buf, "%llx", ull);  // Add missing `ull`
0
source

All Articles