Google Search

Saturday, October 24, 2015

C program to convert float to binary

Following steps are taken to convert float to binary:
1.) From the floating point number, separate the integral and fractional number to different variables.
2.) Integral number can be converted to Binary, by dividing the number by 2, and storing the remainder values from Least significant bit(LSB) to most significant bit(MSB), till the number Quotient does not equal to zero value.
3.) Fractional number can be converted to binary, by multiplying the fractional decimal number by 2 and storing the integral value. Repeating the multiplication step by 2 over the fractional digits on the resultant value. Note:
C program to convert float to binary
‪#‎include‬<stdio.h>
#include<conio.h>
int main()
{
int integral, binaryInt = 0, i = 1;
float binaryFract = 0, k =0.1f, fractional, temp1, binaryTotal, f;
printf("***** Convert float to binary *******\n");
printf("\nEnter float value : ");
scanf("%f",&f);
//Separating the integral value from the floating point variable
integral = (int)f;
//Separating the fractional value from the variable
fractional = f - (int)f;
//Loop for converting decimal to binary
while(integral>0)
{
binaryInt = binaryInt + integral % 2 * i;
i = i * 10;
integral = integral / 2;
}
//Loop for converting Fractional value to binary
while(k>0.00000001)
{
temp1 = fractional *2;
binaryFract = binaryFract+((int)temp1)*k;
fractional = temp1 - (int)temp1;
k = k / 10;
}
//Combining both the integral and fractional binary value.
binaryTotal = binaryInt +binaryFract;
printf(" \nbinary equivalent = %lf\n\n\n\n\n", binaryTotal);
}

No comments:

Post a Comment