Converting an ull to an mpz_t

一世执手 提交于 2019-12-13 05:48:50

问题


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?


回答1:


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`


来源:https://stackoverflow.com/questions/18416425/converting-an-ull-to-an-mpz-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!