I want to initialize a mpz_t
variable in gmp with a very large value like a 1024 bit large integer. How can I do so ? I am new to gmp. Any help would be appreciated.
Asked
Active
Viewed 1.0k times
5
-
What do you want to initialize it with? A given number? A random number? Zero? In what form is your initial data? – Kerrek SB Jul 13 '11 at 21:55
-
i want to intialize with a given number – XyZ Jul 14 '11 at 11:02
-
Well, yes, but how are you given that number -- as a binary, as an ASCII string of numerals, etc. – Kerrek SB Jul 14 '11 at 11:03
-
a string of numerals would do – XyZ Jul 14 '11 at 11:12
-
Then it's trivial, use the constructor. I'll post. Edit: Oh, wait, this is C, not C++... editing! – Kerrek SB Jul 14 '11 at 11:13
2 Answers
7
Use mpz_import
. For example:
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);

Adam Rosenfield
- 390,455
- 97
- 512
- 589
3
To initialize a GMP integer from a string in C++, you can use libgmp++
and directly use a constructor:
#include <gmpxx.h>
const std::string my_number = "12345678901234567890";
mpz_class n(my_number); // done!
If you still need the raw mpz_t
type, say n.get_mpz_t()
.
In C, you have to spell it out 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.

Kerrek SB
- 464,522
- 92
- 875
- 1,084