6
votes

How do we convert mpz_t to std::string?

mpz_t Var;

// Var = 5000
mpz_init_set_ui( Var, 5000 );

std::string Str = "";
// Convert Var to std::string?

mpz_clear( Var );
1
Look at mpz_class::get_str().Marc Glisse
Build with --enable-cxx and include "gmpxx.h" to use the solution by @MarcGlisse.Brett Hale

1 Answers

14
votes

You're looking for mpz_get_str:

char * tmp = mpz_get_str(NULL,10,Var);
std::string Str = tmp;

// In order to free the memory we need to get the right free function:
void (*freefunc)(void *, size_t);
mp_get_memory_functions (NULL, NULL, &freefunc);

// In order to use free one needs to give both the pointer and the block
// size. For tmp this is strlen(tmp) + 1, see [1].
freefunc(tmp, strlen(tmp) + 1);

However, you shouldn't use mpz_t in a C++ program. Use mpz_class instead, since it provides the get_str() method, which actually returns a std::string and not a pointer to some allocated memory.