Home › Forums › C Programming › base conversion › Reply To: base conversion
April 28, 2008 at 1:23 pm
#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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #include <stdio.h><br /> #include <stdlib.h><br /> int xy(int x,int y)<br /> {<br /> int r=1,i;<br /> <br /> for (i=0;i<y;i++)<br /> {<br /> r*=x;<br /> }<br /> <br /> return r;<br /> }<br /> <br /> int my_atoi(char *s,int base)<br /> {<br /> int r=0,i,j,pos=0;<br /> <br /> for (j=0;j<80 && s[j]!=0 && s[j]>='0' && s[j]<='9';j++);<br /> <br /> for (i=j-1;i>=0;i--)<br /> {<br /> r+=(s-'0')*xy(base,pos);<br /> pos++;<br /> }<br /> <br /> return r;<br /> }<br /> <br /> int main()<br /> {<br /> char buff[83];<br /> int num,b1,b2;<br /> <br /> printf("from base:");<br /> fgets(buff,80,stdin);<br /> b1=atoi(buff);<br /> <br /> printf(" to base:");<br /> fgets(buff,80,stdin);<br /> b2=atoi(buff);<br /> <br /> printf("Number:");<br /> fgets(buff,80,stdin);<br /> num=my_atoi(buff,b1);<br /> <br /> itoa(num,buff,b2);<br /> <br /> printf("nresult is %sn",buff);<br /> <br /> return 0;<br /> } |