Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - MPIR: mpz_t to std::string?

Tags:

c++

gmp

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 );
like image 616
Robert Wish Avatar asked Mar 28 '13 20:03

Robert Wish


1 Answers

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.

like image 177
Zeta Avatar answered Oct 10 '22 10:10

Zeta