I have just recently started learning C. I wrote a very short program that converts between decimal and binary. I wanted to try and write a code that converts between decimal and any base (up until 36). However, my code just prints out garbage.
#include <stdio.h>
#include <string.h>
void printBase(int n, int k, int i, char a[])
{
int placeholder;
if (n != 0)
{
//return n % 2 + 10 * printBinary(n / 2);
placeholder=(char)(n%k);
if(placeholder>=10)
{
a[i] = (char)(placeholder - 10) + 'A';
} else {
a[i] = (char)placeholder;
}
i++;
printBase(n/2, k, i, a);
}
for (i=0; a[i]!='\0'; i++)
{
printf("%c", a[i]);
}
return;
}
void reverse(char fromStr[], char toStr[])
{
int i, j=0;
i=getchar();
for (i=0; fromStr[i]!='\0'; i++)
{
j++;
}
i=0;
while (j>=0)
{
toStr[i]=fromStr[j];
i++;
j--;
}
printf("%s", toStr);
}
int main()
{
int n, k;
char a[81], b[81];
setvbuf(stdout, NULL, _IONBF, 0);
printf("Enter a deicmal number you want to convert to binary: ");
scanf("%i", &n);
fflush(stdout);
printf("Enter a base: ");
scanf("%i", &k);
printBase(n, k, 0, a);
//printf("%s", a);
//reverse(a, b);
return 0;
}
I thought the problem was with my reverse function but it works fine outside of this code. Even when I print out string a inside the printBase function it prints out garbage. What is the problem here?
printBase(n/2, k, i, a);
should beprintBase(n/k, k, i, a);
. – Mohamedmohammada[i] = (char)placeholder + '0';
inelse
, but that doesn't fix your problem. – Backbendreverse
function is indeed also incorrect. The null termination character ends up intoStr[0]
instead of at the end. Try changing thewhile
loop toi = 0; while (j > 0) { toStr[i] = fromStr[j - 1]; i++; j--; } toStr[i] = '\0';
– Chlordane