How to initialize mpz_t in gmp with a 1024-bit number from a character string?

I want to initialize a variable mpz_tin gmp with a very large value, for example a 1024-bit large integer. How can i do this? I am new to gmp. Any help would be appreciated.

+5
source share
2 answers

Use mpz_import. For instance:

uint8_t input[128];
mpz_t z;
mpz_init(z);

// Convert the 1024-bit number 'input' into an mpz_t, with the most significant byte
// first and using native endianness within each byte.
mpz_import(z, sizeof(input), 1, sizeof(input[0]), 0, 0, input);
+5
source

To initialize a GMP integer from a string in C ++, you can use libgmp++and use the constructor directly:

#include <gmpxx.h>

const std::string my_number = "12345678901234567890";

mpz_class n(my_number); // done!

If you still need the raw type mpz_t, let's say n.get_mpz_t().

In C, you should write it like this:

#include <gmp.h>

const char * const my_number = "12345678901234567890";
int err;

mpz_t n;
mpz_init(n);
err = mpz_set_str(n, my_number);    /* check that err == 0 ! */

/* ... */

mpz_clear(n);

See the documentation for further ways to initialize integers.

+2

All Articles