8

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 );
Marc Glisse
  • 7,550
  • 2
  • 30
  • 53
Robert Wish
  • 155
  • 2
  • 9

1 Answers1

15

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.

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • You should not use free on the memory returned by mpz_get_str, you need to query the allocation functions with `mp_get_memory_functions`. – Marc Glisse Mar 28 '13 at 20:45
  • @MarcGlisse: I know, but I wanted to simplify that example. Also, if he didn't change the memory functions the default deallocater should be `free`. Other than that, he should simply use the C++ classes. – Zeta Mar 28 '13 at 20:46
  • @MarcGlisse I'd love to see an example on how to use `mp_get_memory_functions` in order to destroy the `char *` returned by `mpz_get_str`. Could you please provide one? – Mihai Todor Apr 04 '13 at 17:03
  • There is one in `gmpxx.h`. – Marc Glisse Apr 04 '13 at 18:15
  • I should have added `mp_get_memory_functions` in the first place, that would have saved you both some time, sorry. – Zeta Apr 04 '13 at 19:56
  • This is still invalid, at least sunCC would reject this (the typedef with extern "C" in gmpxx.h is important), although most other compilers would accept it. I agree that it is a pain. – Marc Glisse Apr 04 '13 at 21:53
  • @MarcGlisse: Feel free to edit it. I wouldn't use this snippet ever, since mixing `mpz_get_str` with `std::string` simply feels wrong: *"Other than that, he should simply use the C++ classes."* – Zeta Apr 04 '13 at 21:57