I have a number that I would like to convert to binary (from decimal) in C.
I would like my binary to always be in 5 bits (the decimal will never exceed 31). I alrea
#include
#include
char numstr[9024];
int i = 0;
void format(int n, int base);
void printreverse(char *s);
int main()
{
int testnum = 312; // some random test number
format(testnum, 2); // 2 for binary
printreverse(numstr);
putchar('\n');
return 0;
}
void format(int n, int base)
{
if (n > 0) {
char tmp = (n % base) + '0';
numstr[i++] = tmp;
// If we put this above other two we don't need printreverse,
// But then we will have unwanted results in other places of numstr if we can't reset it
format(n/base, base);
} else
numstr[i] = '\0'; // terminating character
}
void printreverse(char *s)
{
long len = strlen(s);
while (len-->0)
putchar(s[len]);
}