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

c, floating-point, floating-point-conversion

Solution

This piece of code behaves abnormally: I added some simple print statement

  while(q>0)
  {
     double i;
     main=q*10.0;
     q=modf(main, &i); //extration of frational part(q) and integer part(i)
     cout << "main = " << main << " frac part " << q << " int part " << i << endl;
     cin.get();
     dec=dec+i*pow(2,-t);
     t++;
  }

When you input 1101.11, the following output shown:

Enter binary number to convert(e.g: 1101.11 which will be 13.75 in decimal):
1101.11
bin in main 1101.11
p  1101 q 0.11

//inside the above while loop code
main = 1.1 frac part 0.1 int part 1
main = 1 frac part 1 int part 0  //^^^^^Error, given main=1, it should output integer part 1, fraction part 0
main = 10 frac part 1 int part 9  //^^^^^same strange error here, it should exit while already

So you got wrong result. I tested `modf` separately with input 1, it gave correct result.

So my guess is that you are reading the binary number as double, then tries to convert this double to binary back. There might be something going on under the hood for the precision of number though it shows that it is `1101.11`. As suggested by @Useless, You may need to read the number as a string, figure out the substring before and after the decimal point `.` Then convert this two part into decimal separately.

Problem

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; } ```

Original source