reading binary file content into an mpz_t variable

foxmuldrster at foxmuldrster at
Mon Jan 17 10:06:30 CET 2011


I'm typing all this on my phone, and am also a relative GMP newbie, surely  
unable to answer these questions as skillfully as the others  here (should  
they ever choose to do so), but to my understanding:

1) Find out how many bits you'll need (file size * 8 most likely),

2) Initialize your GMP variable to that many bits of precision,

3) fread your raw file to that member variable which is the pointer (am on  
phone and do not remember its name  off the top of my head),

4) Set the exponent to 0.

For saving existing data, save exponent and precision and bits in some known  
manner before freeing the variable.

To re-read previously saved data, initialize as indicated, then populate as  
shown in steps above, but restore exponent.

I hope someone else in this list will correct my steps if I am wrong.

I also suggest switching to MPFR as it uses exactly the precision specified,  
rather than at least that many.

- Rick

-----Original message-----
From: Erick Paquin <info at>
To: gmp mailing list <gmp-discuss at>
Sent: Sun, Jan 16, 2011 23:05:20 GMT+00:00
Subject: reading binary file content into an mpz_t variable

Hi Everyone,

Please bear with me as my programming skills are still relatively new.

I've tried a few things but I cannot seem to do what I want.

I would basically like to read the "entire" content of a file (its
hex/binary content) into an mpz_t variable for later processing.

I've tried with both the mpz_inp_str and the mpz_inp_raw functions and when
I try to see the number of bytes read from these functions it always either
returns 0 (as if an error occurred) or it crashes the application with a
memory segmentation fault.

Actually I am not also 100% sure of how to "read" the size_t returned value
from the gmp functions (do you assign the function to an int variable and
read it?). Any help on that too would be awesome.

How would you go about in the simplest way possible read the entire content
of a file into an mpz_t variable?

I've also tried with fread which actually works but then to transfer the
content of my fread into an mpz_t variable I couldn't find how.

Any tips?


Erick P.
gmp-discuss mailing list
gmp-discuss at

More information about the gmp-discuss mailing list