GMP-将64位整数存储在mpz_t/mpz_class中,并返回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()
和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);
现场演示
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- 如何在C++中将整数转换为其数字数组