Hello friends,
Today I’m going to explain you guys that how to convert binary numbers to decimal and vice versa.
So let first talk about what is binary numbers and what is decimal numbers. So basically binary numbers are numbers with base 2 and the decimal numbers are numbers with base 10
//program to convert binary numbers to decimal and vice versa
#include<stdio.h> //library for standard input and output function
#include<stdio.h> //library for standard input and output function
#include<math.h> //library for standard mathematics function
int binary(int,float); //function for converting binary values to decimal
int decimal(int,float); // function for converting decimal values to binary
int main()
{
int ch,i;
float x,j;
printf(“this program is accurate upto 5 digit after decimal point\n”);
printf(“what number you want to enter ?? \n1> binary\n2>decimal\n”);
scanf(“%d”,&ch);
switch(ch) //switch is somewhat similar to if elseif ladder difference lies in their speed as switch is directly execute required step whereas ladder check all the step upto which condition is satisfies
{
case 1:
printf(“enter binary number =”);
scanf(“%f”,&x);
i=x;
j=x-i;
binary(i,j);
break;
case 2:
printf(“enter decimal number =”);
scanf(“%f”,&x);
i=x;
j=x-i;
decimal(i,j);
break;
}
return 0; //necessary because main function never return any values other than 0
}
scanf(“%d”,&ch);
switch(ch) //switch is somewhat similar to if elseif ladder difference lies in their speed as switch is directly execute required step whereas ladder check all the step upto which condition is satisfies
{
case 1:
printf(“enter binary number =”);
scanf(“%f”,&x);
i=x;
j=x-i;
binary(i,j);
break;
case 2:
printf(“enter decimal number =”);
scanf(“%f”,&x);
i=x;
j=x-i;
decimal(i,j);
break;
}
return 0; //necessary because main function never return any values other than 0
}
int binary(int i,float j)
{
int a,b=0,c=0;
float d=0;
while(i>0)
{
a=i%10; //algorithm for converting binary numbers to decimal number
if(a==1) //algorithm for converting binary number left to the decimal point
b=b+pow(2,c); //pow(a,b) is a standard mathematics function used for calculating power as in this case it shows a^2
i=i/10;
c++;
}
c=-1;
while(c>-10) //algorithm for converting binary number after the decimal point
{
a=j*10;
j=j*10;
if(a==1)
{
j=j-1;
d=d+pow(2,c);
}
c–;
}
printf(“%f\n”,b+d);
return 0;
}
return 0;
}
int decimal(int i,float j)
{
int a,b=0,c=0;
while(i>0)
{
a=i%2;
b=b+pow(10,c)*a;
i=i/2;
c++;
}
printf(“%d”,b);
printf(“.”);
b=0;
c=0;
while(c<5)
{
j=j*2;
a=j;
if(j>1)
{
j=j-1;
}
if((c!=0&&b==0)
printf(“0”);
b=b*10+a;
c++;
}
printf(“%d”,b);
return 0;
}