posted on January 26, 2009
This is some C code that I wrote to convert a decimal integer to its binary equivalent. Most programs written to do so convert the decimal to a string, or an array, of the consecutive remainders modulo 2, which is then printed out in reverse order to get the binary equivalent. However I wanted an integer output of the binary equivalent. So this is what I did.
#include<stdio.h>
int power(int power)
{
int i,p=1;
for(i=0;i<power;i++)
*=10;
preturn p;
}
int dectobin(int dec)
{
int bin=0,s[15],i=0,j;
while(dec!=0)
{
[i]=dec%2;
s/=2;
dec++;
i}
for(j=i-1;j>=0;j--)
+=s[j]*power(j);
binreturn bin;
}
int main()
{
int num=114;
("The binary equivalent of %d is %d\n",num,dectobin(num));
printfreturn 0;
}