Advertisement
noor017

Floating Binary to Floating Decimal Conversion

Jun 27th, 2015
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.53 KB | None | 0 0
  1. ///***************Floating Binary to Floating Decimal Conversion***************///
  2.  
  3. #include<stdio.h>
  4. #include<string.h>
  5. #include<math.h>
  6.  
  7. int main()
  8. {
  9.     char number[100];
  10.  
  11.     puts("---------------------------------");
  12.     printf("Enter a binary number: ");
  13.  
  14.     while(scanf("%s", &number))
  15.     {
  16.  
  17.         int i, j=0, len, loopLimit, decimalPointIndex=-1, beforeDecimalPoint=0;
  18.         double decimalNumber, afterDecimalPoint=0.00;
  19.  
  20.         len=strlen(number);
  21.         for(i=0; i<len; i++)
  22.         {
  23.             if(number[i]=='.')
  24.             {
  25.                 decimalPointIndex=i;
  26.                 break;
  27.             }
  28.         }
  29.  
  30.         if(decimalPointIndex==-1)
  31.         {
  32.             loopLimit=len;
  33.         }
  34.  
  35.         else
  36.         {
  37.             loopLimit=decimalPointIndex;
  38.         }
  39.  
  40.         for(i=loopLimit-1; i>=0; i--)
  41.         {
  42.             if(number[i]=='1')
  43.             {
  44.                 beforeDecimalPoint+=(pow(2,j));
  45.             }
  46.  
  47.         ++j;
  48.  
  49.         }
  50.  
  51.         if(decimalPointIndex!=-1)
  52.         {
  53.             j=-1;
  54.             for(i=loopLimit+1; i<len; i++)
  55.             {
  56.                 if(number[i]=='1')
  57.                 {
  58.                     afterDecimalPoint+=(pow(2.00,(j*1.0)));
  59.                 }
  60.  
  61.             --j;
  62.  
  63.             }
  64.         }
  65.  
  66.         decimalNumber=beforeDecimalPoint+afterDecimalPoint;
  67.         printf("%s , in decimal: %lf\n\n", number, decimalNumber);
  68.  
  69.         puts("---------------------------------");
  70.         printf("Enter a binary number: ");
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement