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?
Based on your code, the following does what you want. It places in a
a reverse conversion that must still be printed backwards:
void convertBase(int n, int k, char a[])
{
int j, i=0, sign= 0;
if (n==0) a[i++]='0';
if (n<0 ) {sign= -1; n= -n;}
while (n>0) {
j= n%k;
if (j<10)
a[i]= j+'0';
else
a[i]= j+'A';
n= n/k;
i++;
}
if (sign== -1) a[i++]= '-';
a[i]= 0;
}
And here is revert:
void revStr(char *s)
{
char c;
int i=0, j=0;
while (s[i]) i++; i--;
while (i>j) {
c= s[j];
s[j]=s[i];
s[i]= c;
i--; j++;
}
}