GMP-将64位整数存储在mpz_t/mpz_class中,并返回64位整数

GMP - Store 64 bit interger in mpz_t/mpz_class and get 64 bit integers back

本文关键字:mpz 整数 64位 返回 class 存储 GMP-      更新时间:2023-10-16

我想将64位整数的值分配到mpz_class/mpz_t变量中,然后再获取64位整数。然而,GMP仅为32位及以下整数提供此功能。

那么,我该如何将64位整数转换为mpz_class/mpz_t变量,反之亦然。(有符号整数和无符号整数都需要它(

这可以通过mpz_import()mpz_export()函数来实现
代码样本(在LP64数据模型上测试(:

using Type = int64_t;
// We start with some 64bit integer
const Type builtIn64 = std::numeric_limits<Type>::min();
std::cout << builtIn64 << 'n';
// Import the integer into the mpz_class
mpz_t mpzNum;
mpz_init(mpzNum);
mpz_import(mpzNum, 1, 1, sizeof(Type), 0, 0, &builtIn64);
if (builtIn64 < 0) {
mpz_neg(mpzNum, mpzNum);
}
std::cout << mpz_class(mpzNum) << 'n';
// Export the mpz_t value to a buffer allocated by the function and given
// the word size, get also the number of words required to hold the value
const size_t wordSize = sizeof(Type);
size_t wordCount = 0;
void* outRaw = mpz_export(nullptr, &wordCount, 1, wordSize, 0, 0, mpzNum);
// Make sure that our integer type can still hold the value
if (wordCount == 1) {
const Type out = *static_cast<Type*>(outRaw);
std::cout << out << 'n';
}
// Free the allocated memory by mpz_export
void (*freeFunction)(void*, size_t);
mp_get_memory_functions(nullptr, nullptr, &freeFunction);
freeFunction(outRaw, wordCount * wordSize);
// Don't forget to free the allocated memory
mpz_clear(mpzNum);

现场演示