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

时间:2013-03-28 20:24:16

标签: c++ gmp

我们如何将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 );

1 个答案:

答案 0 :(得分:10)

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

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