C/binary in c
Expert: Prince M. Premnath - 9/20/2007
QuestionCan you show me how to create a decimal to binary conversion program in C as basic as possible? Our teacher hasn't taught us anything, but he wants us to somehow do this.
Thank you
AnswerDear Justin !
Ya of course thats possible with C , here im presenting you a simple program , hope it will meet your expectation
#include <stdio.h>
void dec2bin(long decimal, char *binary);
int main()
{
long decimal;
char binary[80];
printf("\n\n Enter an integer value : ");
scanf("%ld",&decimal);
dec2bin(decimal,binary);
printf("\n The binary value of %ld is %s \n",decimal,binary);
getchar();
return 0;
}
void dec2bin(long decimal, char *binary)
{
int k = 0, n = 0;
int neg_flag = 0;
int remain;
int old_decimal;
char temp[80];
if (decimal < 0)
{
decimal = -decimal;
neg_flag = 1;
}
do
{
remain = decimal % 2;
decimal = decimal / 2;
temp[k++] = remain + '0';
} while (decimal > 0);
if (neg_flag)
temp[k++] = '-'; // add - sign
else
temp[k++] = ' '; // space
while (k >= 0)
binary[n++] = temp[--k];
binary[n-1] = 0;
}
Thanks and Regards !
Prince M. Premnath