Correct algorithm to convert binary floating point "1101.11" into decimal (13.75)?

Biswajit Paul picture Biswajit Paul · Apr 2, 2013 · Viewed 9.1k times · Source

I have written a program in C to convert a floating point number represented in binary (1101.11) into a decimal (13.75).

However, I cannot seem to get the correct value out of the algorithm.

What is the correct method for converting a binary floating point number into a decimal?

I am using Dev CPP compiler (32 bit). The algorithm is defined below:

void b2d(double p, double q )
{
   double rem, dec=0, main, f, i, t=0;

   /* integer part operation */    
   while ( p >= 1 )
   {
     rem = (int)fmod(p, 10);
     p = (int)(p / 10);
     dec = dec + rem * pow(2, t);
     t++;
   }

   /* fractional part operation */
   t = 1; //assigning '1' to use 't' in new operation
   while( q > 0 )
   {
     main = q * 10;
     q = modf(main, &i); //extration of frational part(q) and integer part(i)
     dec = dec+i*pow(2, -t);
     t++;
   }

   printf("\nthe decimal value=%lf\n",dec); //prints the final output
}

int main()
{
   double bin, a, f;

   printf("Enter binary number to convert:\n");
   scanf("%lf",&bin);

   /* separation of integer part and decimal part */
   a = (int)bin;
   f = bin - a;       
   b2d(a, f); // function calling for conversion

   getch();
   return 0;
}

Answer

Useless picture Useless · Apr 2, 2013

You are not, as you believe, reading "1101.11" as a floating point number represented in binary. You are reading it as a base-10 floating point number converted into an IEEE double-precision floating-point value, and then trying to change the base.

The inherent imprecision of this intermediate step is the reason for your problem.

A better approach, as suggested by Vicky, is to:

  1. read "1101.11" as a string or line of text
  2. convert the whole and fractional parts (whole=b1101=13 and numerator=b11=3, denominator=4)
  3. re-combine these into whole + numerator/denominator = 13.75