0

I saw the post at question mpz_t to unsigned long long conversion (gmp lib) and Chris Jester-Young 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 here is that, as stated in How to convert GMP C parameter convention into something more natural? mpz_t is an array. How can I circumvent this(Without doing so strange 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 wrong results.

And, is his code legal C?

Community
  • 1
  • 1
chubakueno
  • 565
  • 4
  • 18
  • Uh, you are not even using `ull` in your functions... – Marc Glisse Aug 24 '13 at 20:53
  • You need to show how you are using those functions. Also, I don't see the point of introducing a result variable (which you forget to free) that you're just going to copy into val. – Marc Glisse Aug 24 '13 at 20:57
  • @MarcGlisse I just copy-pasted his code and just added the parameter *mpz_t val* the last line to have more control over the problem(less variables). What is wrong with his code? – chubakueno Aug 25 '13 at 01:21

1 Answers1

0

OP is not using snprintf() correctly. Need to pass ull.

Use

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`
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256