Thursday, October 29, 2009

Converting decimal to binary

Write a function to find the binary equivalent of a given decimal and display it.

Reference:
http://en.wikipedia.org/wiki/Binary_numeral_system

From the above article, the pattern is that for every power of 2(i.e 2²,2³), the number of digits in the binary increases by 1. Therefore the pattern is 2¹(decimal)= 10¹(binary)
2²(decimal)=10² (binary)
2³(decimal)=10³(binary) and so on.




#include math.h (include arrows)
void main()
{
int a,b;
printf("\nInput a number to find its binary equivalent");
scanf("%d",&a);
b=bina(a);
printf("\nThe binary equivalent of %d is %d",a,b);
}
/*Let our x be 5*/
bina(int x)
{
int a,b,c,d;

for(d=0;x>0;x-=c)
{

for(a=2,b=0,c=0;x>=c;b++)
{
if(x==0)
return(0);


/*|First loop|For x= 5, the value of c will reach 8 which is 2power3 and thus b=3*/
/*|Second loop|For x=1, the value of c will reach 2 which is 2power1 and thus b=1*/

c=pow(a,b);
}
/*|First loop|When we exit the loop b++ is executed so b=4*/
/*|Second loop|When we exit loop b++ is executed so b=2*/

b=b-2;
/*|First loop|b=2*/
/*|Second loop|b=0*/
c=pow(a,b);
/*|1st|c=4*/
/*|2nd|c=1*/
d=d+pow(10,b);
/*|1st|d=100*/
/*|2nd|d=100+1=101*/
}
/*|1st|On exiting the loop x=x-c: 5-4=1 so x =1*/
/*|2nd|On exiting loop x=x-c=1-1=0 so the for loop is exited since x must be >0*/

return(d);
}


(Without explanation)


#include math.h (include arrows)
void main()
{
int a,b;
printf("\nInput a number to find its binary equivalent");
scanf("%d",&a);
b=bina(a);
printf("\nThe binary equivalent of %d is %d",a,b);
}

bina(int x)
{
int a,b,c,d;

for(d=0;x>0;x-=c)
{

for(a=2,b=0,c=0;x>=c;b++)
{
if(x==0)
return(0);



c=pow(a,b);
}

b=b-2;
c=pow(a,b);
d=d+pow(10,b);
}

return(d);
}

No comments:

Post a Comment