Code:
char* dec2bin(int decimal);
int main()
{
int x = 0;
char* ans;
int i;
for (i=0; i<10; i++)
{
ans = dec2bin(x);
printf("x = %d ===> %s\n", x, ans);
x++;
}
return 0;
}
char* dec2bin(int decimal)
{
int k = 0, n = 0;
int neg_flag = 0;
int remain;
char temp[80];
char binary[80];
// take care of negative input
if (decimal < 0)
{
decimal = -decimal;
neg_flag = 1;
}
do
{
remain = decimal % 2;
decimal = decimal / 2; // whittle down decimal
temp[k++] = remain + 0x30; // makes characters 0 or 1
} while (decimal > 0);
if (neg_flag)
temp[k++] = '-'; // add back - sign
else
temp[k++] = ' '; // or space
while (k >= 0)
{
binary[n++] = temp[--k]; // reverse spelling
}
binary[n-1] = 0; // end with NULL
return binary;
}
This is exactly what I need...in essence. But I am returning address of a local variable, how to get around it? I need it to return a value, not pass a variable in.
Also, for some reason, my 1st value doesn't get printed. I am guessing its coz of the local variable problem, but I could be wrond. Meh?!?!
Thhanks a lot guys.