c++ - gmp库中的移位操作

标签 c++

我必须执行左移和右移,并且我正在使用 gmp 库。

我使用了代码

#include<gmp.h>

mpz_t t;
mpz_init2(t,125);
mpz_set_ui(t,31);
mpz_mul_2exp(t , t , 35);

它给我的 t 值为零。谁能帮帮我吗?

最佳答案

尝试使用 mpz_init 而不是 mpz_init2。

实际上,它应该可以与您的方法配合使用,因为该操作不会超过您为 t 分配的 125 位。我现在刚刚测试过。你如何检查结果?你用过gmp_printf("%Zd\n", t);吗?

要将 GMP 整数的字符串表示形式转换为 std::string,您可以执行以下操作:

//get a pointer to GMP's internal memory deallocator function
void (*deallocator)(void *, size_t);
mp_get_memory_functions(NULL, NULL, &deallocator);

//get the string representation of input in binary
char *data = mpz_get_str(NULL, 2, input.data);

std::string output(data);

//deallocate data, including the terminator character
//calling std::free on the char * returned by mpz_get_str is a bad idea, because it is initialised internally by GMP
(*deallocator)((void *)data, std::char_traits<char>::length(data) + 1);

2018 年更新:上述代码的先前版本完全错误。当前版本应该是正确的。

关于c++ - gmp库中的移位操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11721082/

相关文章:

c++ - 命令行上的 vcpkg 设置错误

c++ - windows编程中如何触发最大化/最小化

c++ - 我的字母字符串管理器无法正确保存到文件中

c++ - 如何通过鼠标移动使OpenGL相机在SFML中移动

c++ - 在 Visual Studio 中构建 MATLAB mex 文件给出 "LNK2019 unresolved external symbol _mexPrintf referenced in function mexFunction"?

c++ - Qt paintEvent 崩溃

c++ - 编译器无法通过 ADL 找到基类方法

c++ - 生成伪随机 16 位整数

c++ - 优先队列中的比较器功能

c++ - 应该在程序结束时调用 FreeLibrary 吗?