Search code examples
c++gmp

Convert mpz_t to binary representation


I'm using mpz_t for big numbers. I need to convert the mpz_t to binary representation. I tried to use the mpz_export, but the returned array contains only 0s.

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);

Solution

  • Using gmpxx (since it's taged as c++)

    #include <iostream>
    #include <gmpxx.h>
    
    int main()
    {
        mpz_class a("123456789");
        std::cout << a.get_str(2) << std::endl; //base 2 representation
    }
    

    There should be equivalent function in plain GMP