# mpf_get_str

Sun Oct 6 08:55:48 CEST 2013

```Hi.
I try to convert decimal fration to binary using mpf_get_str .
Example input 1/6 should give 0.00101010101010101

How can I do that using gmp ?
Below is my program.
it gives :
101010101010101010101010101010101010101010101010101010101010101011
exponent : -2

TIA

====

/*

C programme

gcc r.c -lgmp
./a.out

http://gmplib.org/manual/Rational-Number-Functions.html#Rational-Number-Functions

a rational number 1 / 6 is in a canonical form ( decimal fraction) : 1/6
numerator of rational number = 1
denominator of rational number = 6
binary rational (  string ) : 1/110
decimal floating point number : 0.166666666666666666667
binary floating (  string ) :
101010101010101010101010101010101010101010101010101010101010101011
exponent : -2
f=101010101010101010101010101010101010101010101010101010101010101011f*2^-2

should be 0.0(01)

*/

#include <stdio.h>
#include <gmp.h>

// input = num/den
unsigned int num = 1;
unsigned int den = 6;

int main ()
{

mpq_t q;   // rational number;
int b =2 ; // base of numeral system
mpz_t  n ;
mpz_t  d ;
mpf_t  f ;
char  *sr;
char  *sf;
mp_exp_t exponent ; // holds the exponent for the result string

// init and set variables
mpq_init (q); // Initialize r and set it to 0/1.
mpf_init (f);
mpz_init_set_ui(n,num);
mpz_init_set_ui(d,den);
mpq_set_num(q,n);
mpq_set_den(q,d);
mpq_canonicalize (q); // It is the responsibility of the user
to canonicalize the assigned variable before any arithmetic operations
are performed on that variable.
mpf_set_q(f,q);

// convertions
sr = mpq_get_str (NULL, b, q); // rational number = fraction :
from decimal to binary
// If str is NULL, the result string is allocated using the
current allocation function
sf = mpf_get_str (NULL, &exponent, b, 0, f); // floating point
number : from decimal to binary
//  If n_digits is 0 then that accurate maximum number of
digits are generated.

// print
gmp_printf ("a rational number %Zd / %Zd is in a canonical form
( decimal fraction) : %Qd\n",n,d, q); //
gmp_printf(" numerator of rational number = %Zd \n",
mpq_numref(q)); //
gmp_printf(" denominator of rational number = %Zd \n",
mpq_denref(q)); //
gmp_printf ("  binary rational (  string ) : %s \n", sr); //
gmp_printf ("  decimal floating point number : %.Ff \n", f); //
gmp_printf ("  binary floating (  string ) : %s \n", sf); //
gmp_printf ("  exponent : %ld \n", exponent); //
printf ("f=%sf*%d^%ld\n", sf,b, exponent);

// clear memory
mpq_clear (q);
mpz_clear (n);
mpz_clear (d);
mpf_clear (f);

return 0;
}
```