GMP - 在 mpz_t/mpz_class 中存储 64 位整数并取回 64 位整数
GMP - Store 64 bit interger in mpz_t/mpz_class and get 64 bit integers back
我想将 64 位整数的值分配给 mpz_class
/mpz_t
变量,然后再取回 64 位整数。但是 GMP 只为 32 位和更低的整数提供此功能。
那么我如何将 64 位整数转换为 mpz_class
/mpz_t
变量,反之亦然。 (我需要它用于有符号和无符号整数)
这可以通过 mpz_import()
and 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);
我想将 64 位整数的值分配给 mpz_class
/mpz_t
变量,然后再取回 64 位整数。但是 GMP 只为 32 位和更低的整数提供此功能。
那么我如何将 64 位整数转换为 mpz_class
/mpz_t
变量,反之亦然。 (我需要它用于有符号和无符号整数)
这可以通过 mpz_import()
and 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);