将 mpz_t 转换为二进制表示

Convert mpz_t to binary representation

我对大数字使用 mpz_t。我需要将 mpz_t 转换为二进制表示形式。我尝试使用 mpz_export,但返回的数组仅包含 0。

mpz_t test;
mpz_init(test);
string myString = "173065661579367924163593258659639227443747684437943794002725938880375168921999825584315046";
    mpz_set_str(test,myString.c_str(),10);
    int size = mpz_sizeinbase(test,2);
    cout << "size is : "<< size<<endl;
    byte *rop = new byte[size];
    mpz_export(rop,NULL,1,sizeof(rop),1,0,test);

使用 gmpxx(因为它被标记为 c++

#include <iostream>
#include <gmpxx.h>

int main()
{
    mpz_class a("123456789");
    std::cout << a.get_str(2) << std::endl; //base 2 representation
}

plain GMP中应该有等价的功能

您的代码中有一个小错误:sizeof(rop) 为 4 或 8,具体取决于您系统上的指针是 4 字节还是 8 字节。您打算传递简单的大小,而不是 sizeof(rop)。

这是一些对我有用的代码,使用 g++ -lgmp -lgmpxx:

#include <stdio.h>
#include <iostream>
#include <gmpxx.h>

int main()
{
    mpz_class a("173065661579367924163593258659639227443747684437943794002725938880375168921999825584315046");
    int size = mpz_sizeinbase(a.get_mpz_t(), 256);
    std::cout << "size is : " << size << std::endl;
    unsigned char *rop = new unsigned char[size];
    mpz_export(rop, NULL, 1, 1, 1, 0, a.get_mpz_t());
    for (size_t i = 0; i < size; ++i) {
      printf("%02x", rop[i]);
    }
    std::cout << std::endl;
}