6

我们如何将 mpz_t 转换为 std::string?

mpz_t Var;

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

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

mpz_clear( Var );
4

1 回答 1

14

您正在寻找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);

但是,您不应该mpz_t在 C++ 程序中使用。改为使用mpz_class,因为它提供了get_str()方法,该方法实际上返回 astd::string而不是指向某些已分配内存的指针。

于 2013-03-28T20:34:19.220 回答