Program to Convert Floating Decimal to Binary Using C Language

**NOTE: The following code for “Program to Convert Floating Decimal To Binary Using C language” has been written and performed on Ubuntu OS, To run the following code in Windows on Turbo C, You need to add #include<conio.h> as one of the header files and getch() at the end of the code before main() closing brace “}”.

#include<stdio.h>
void main(){
float a;
double c;
int b,k,l=0,m[20],n,i,count=0,p;
printf("Enter any number:");
scanf("%lf",&c);
b=c;
a=c-b;
printf("%d,%f",b,a);
printf("\n");
while(b!=0){
 n=b%2;
 b/=2;
 m[i]=n; 
 count+=1;i++;
 
}
for(k=count-1;k>=0;k--){
printf("%d",m[k]);
}

printf(".");
for(p=1;p<=8;p++){
a=a*2;
l=a;
printf("%d",l);
if(l==1)
 a=a-l;
 
}
printf("\n");

}

Explanation For the Above Program:

  • Input a floating number from the user ——> c
  • Copy the floating number from c to int variable b —-> b=c;
  • Now take another floating variable to store only the floating part.———->a= b – c;
  • Then take the first integer part which is stored in b and start its conversion.
  • Run the while loop with the condition b is  not equal to Zero ———–> b!=0;
  • Divide the input variable by 2 to get the remainder and store it in another variable———> n = b % 2;
  • Divide the input value again to get the quotient and store it in the input variable itself ——-> b/=2;
  • Store the Remainder in an array variable and increment the index i by 1———->m[i]=n;
  • “count” variable above keep tracks of the number of times the loop runs.———->count+=1;
  • Print the array values using for loop with “k” as a looping variable which runs from backwards “count” to 0. ————>for(k=count;k>=0;k–)
  • Print the array index values.
  • Take the floating values in the next loop.Run it till 8 or more.
  • Multiply the floating number by 2 and store its integer value in an integer variable “l”.—>a=a*2;l=a;
  • check if “l” is equal to 1. If yes then subtract the “l” from “a” —> a = a – l;

OUTPUT :

program to convert floating decimal to binary

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: