Home Forums C Programming base conversion Reply To: base conversion

#3265
Priyansh Agrawal
Participant

This code could do this from base 2-10 to base 2-10. There is a nice function called itoa that converts int to char* and you can specify the base. Unfortunatelly the function atoi has no base-parameter. So I recoded it:

#include 
#include
int xy(int x,int y)
{
int r=1,i;

for (i=0;i {
    r*=x;
}

return r;
}

int my_atoi(char *s,int base)
{
int r=0,i,j,pos=0;

for (j=0;j<80 && s[j]!=0 && s[j]>='0' && s[j]<='9';j++);

for (i=j-1;i>=0;i--)
{
    r+=(s-'0')*xy(base,pos);
    pos++;
}

return r;
}

int main()
{
char buff[83];
int num,b1,b2;

printf("from base:");
fgets(buff,80,stdin);
b1=atoi(buff);

printf(" to base:");
fgets(buff,80,stdin);
b2=atoi(buff);

printf("Number:");
fgets(buff,80,stdin);
num=my_atoi(buff,b1);

itoa(num,buff,b2);

printf("nresult is %sn",buff);

return 0;
}