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?

3
  • Uh, you are not even using ull in your functions... Aug 24, 2013 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. Aug 24, 2013 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, 2013 at 1:21

1 Answer 1

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`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.