There is a function to set a mpz number with a zero-terminated string.
int mpz_set_str (mpz_t rop, const char *str, int base);
But there is no functions for a non-zero terminated string, and I would like to do that avoiding allocations and changes on the string.
int mpz_set_strn (mpz_t rop, const char *str, size_t n, int base);
I found a similar discussion about this on gmp-discuss
In my case, I would like to use part of the string. I've tried to simulate what the mpz_set_str function does in the background, but it seems it didn't work.
#include <gmp.h>
int main(){
const char * str_base16 = "354a546fde";
mpz_t bn;
mp_size_t xsize;
mpz_init(bn);
// setting bn with part of str_base16
mpz_realloc2(bn, 8*4);
xsize = mpn_set_str(bn->_mp_d, (unsigned char *)str_base16, 8, 16);
bn->_mp_size = xsize;
gmp_printf("%ZX\n", bn);
return 0;
}
Output:
337637766
Looking at the source code for
mpz_set_str(), it looks like you can use the low-level functionmpn_set_str()directly, which takes a pointer and length to digits which start at 0 (not the ASCII character'0').