C Program to Convert Binary into Decimal Number

on 26 August 2013

Here is a source code of simple c programming language program to convert a binary number into a decimal number. This program will also convert the fractional parts.


#include<stdio.h>
#define MAX 1000

int main()
{
    double fraDecimal=0.0,dFractional=0.0 ,fraFactor=0.5;
    long dIntegral = 0,bIntegral=0,bFractional[MAX];
    long intFactor=1,remainder,i=0,k=0,flag=0;
    char fraBinary[MAX];

    printf("Enter any fractional binary number: ");
    scanf("%s",&fraBinary);
   
   //Separating the integral and fractional parts
    while(fraBinary[i])
    {
        
         if(fraBinary[i] == '.')
             flag = 1; //If dot is found start taking the fractional part.
         else if(flag==0)
             bIntegral = bIntegral * 10 + (fraBinary[i] -48); /* char - 48 to get the numerical value.*/
         else
              bFractional[k++] = fraBinary[i] -48;
         i++;
    }
   
    while(bIntegral!=0){
        remainder=bIntegral%10;
        dIntegral= dIntegral+remainder*intFactor;
        intFactor=intFactor*2;
        bIntegral=bIntegral/10;
    }
   
    for(i=0;i<k;i++){
         dFractional  = dFractional  + bFractional[i] * fraFactor;
         fraFactor = fraFactor / 2;
    }

    fraDecimal = dIntegral + dFractional ;

    printf("Equivalent decimal value: %Lf",fraDecimal);   
    return 0;
}

Output


Binary to Decimal Program

Note: I have compiled the program using FireCMD shell.

0 comments:

Post a Comment