fractional binary conversion from decimal in c language | CTechnotips


Algorithm:

Algorithm to convert the fractional binary to decimal or floating point binary to decimal:

Step1. First we convert the integral part of binary number to decimal. For this we multiply each digit separately from right side by 1, 2, 4, 8, 16 … respectively then add them this is integral part of decimal number.

Step2. Now we convert the fractional part of binary number to decimal. For this we multiply each digit separately from left side by 1/2, 1/4, 1/8, 1/16 … respectively then add them this is fractional part of decimal number.

Step3: Add the integral and fractional part of decimal number.

Example for floating point binary to decimal:

For example we want to convert the binary number 101111.1101 to decimal number.

Step1: Conversions of 101111 to decimal:

S1:  1 * 1 = 1
S2:  1 * 2 = 2
S3:  1 * 4 = 4
S4:  1 * 8 = 8
S5:  0 * 16 = 0
S6:  1 * 32 = 32

Integral part of decimal number: 1 + 2 + 4+ 8+ 0+ 32 = 47

Step2: Conversions of .1101 to decimal:

S1: 1 * (1/2) = 0.5
S2: 1 * (1/4) = 0.25
S3: 0 * (1/8) = 0
S4: 1 * (1/16) = 0.0625

Fractional part of decimal number = 0.5 + 0.25 + 0 + 0.0625 = 0.8125

So equivalent binary number is: 0.101100

Step 3: So binary value of binary number 101111.1101 will be 47 + 0.8125 = 47.8125


C code for fractional binary to decimal converter:

#include
<stdio.h>

#define MAX 1000


int main(){


 long double fraDecimal=0.0,dFractional=0.0 ,fraFactor=0.5;

    long int dIntegral = 0,bIntegral=0,bFractional[MAX];

    long int intFactor=1,remainder,i=0,k=0,flag=0;

    char fraBinary[MAX];


    printf("Enter any fractional binary number: ");

    scanf("%s",&fraBinary);

   

    while(fraBinary[i]){

        

         if(fraBinary[i] == '.')

             flag = 1;

         else if(flag==0)

             bIntegral = bIntegral * 10 + (fraBinary[i] -48);

         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;

}



Sample output:

Enter any fractional binary number: 11.11
Equivalent decimal value: 3.750000

0 comments:

Post a Comment