简体   繁体   English

mpz_t 到 unsigned long long 的转换(gmp lib)

[英]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.有没有办法将 C 中的 mpz_t 变量转换为 unsigned long long?反过来呢,从 ull 到 mpz_t 怎么样?gmp 库不支持这一点,因为 ull 是 C99 的一部分。 I found this but it's in c++,and I don't know how to code in c++.Thanks in advance.我找到了这个,但它在 c++ 中,我不知道如何在 c++ 中编码。提前致谢。

Here are some functions for translating between unsigned long long and mpz_t .以下是一些用于在unsigned long longmpz_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将粉碎您的堆栈:

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);
}

These functions should work to convert between mpz_t and signed/unsigned long long.这些函数应该可以在 mpz_t 和 signed/unsigned long long 之间进行转换。 They should be reasonably fast since they avoid having to do string processing:它们应该相当快,因为它们避免了必须进行字符串处理:

void mpz_set_sll(mpz_t n, long long sll)
{
    mpz_set_si(n, (int)(sll >> 32));     /* n = (int)sll >> 32 */
    mpz_mul_2exp(n, n, 32 );             /* n <<= 32 */
    mpz_add_ui(n, n, (unsigned int)sll); /* n += (unsigned int)sll */
}

void mpz_set_ull(mpz_t n, unsigned long long ull)
{
    mpz_set_ui(n, (unsigned int)(ull >> 32)); /* n = (unsigned int)(ull >> 32) */
    mpz_mul_2exp(n, n, 32);                   /* n <<= 32 */
    mpz_add_ui(n, n, (unsigned int)ull);      /* n += (unsigned int)ull */
}

unsigned long long mpz_get_ull(mpz_t n)
{
    unsigned int lo, hi;
    mpz_t tmp;

    mpz_init( tmp );
    mpz_mod_2exp( tmp, n, 64 );   /* tmp = (lower 64 bits of n) */

    lo = mpz_get_ui( tmp );       /* lo = tmp & 0xffffffff */ 
    mpz_div_2exp( tmp, tmp, 32 ); /* tmp >>= 32 */
    hi = mpz_get_ui( tmp );       /* hi = tmp & 0xffffffff */

    mpz_clear( tmp );

    return (((unsigned long long)hi) << 32) + lo;
}

long long mpz_get_sll(mpz_t n)
{
    return (long long)mpz_get_ull(n); /* just use unsigned version */
}

The function signatures are supposed to look like native GMP functions. function 签名应该看起来像原生 GMP 函数。 As with other gmpz_set_ functions, these assume the variables passed have been initialised already, but it is easy to change them into gmp_init_set_ style functions.与其他gmpz_set_函数一样,这些假设传递的变量已经初始化,但很容易将它们更改为gmp_init_set_样式函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM