Home › Forums › C Programming › base conversion
- This topic has 2 replies, 3 voices, and was last updated 16 years, 8 months ago by Priyansh Agrawal.
Viewing 2 reply threads
- AuthorPosts
- November 3, 2007 at 5:54 am #2024kenezParticipant
Guys I need to write a program that will convert FROM and TO any bases ranging from 2 to 10.oh bases meaning binary, base 3 numbers, octal etc(up to 10)
The program should prompt for the base “converted to” and the base “converted from”.
Can somebody tell me how I need to go about this and what aspects of C
maybe helpful. I will do the actual coding and report any problems.
Thanks - March 13, 2008 at 11:24 pm #3264yeswanthParticipant
A program to convert a decimal number to its equivalent binary number.
1234567891011121314151617181920#include <stdio.h><br />#include <conio.h><br />void main()<br />{<br />unsigned long dec;<br />int a[25],c=0,i;<br />clrscr();<br />printf("nENTER A DECIMAL NUMBER: ");<br />scanf("%lu",&dec);<br />printf("n%lu IN BINARY FORMAT: ",dec);<br />while(dec>0)<br />{<br />a[c]=dec%2;<br />dec=dec/2;<br />c++;<br />}<br />for(i=c-1;i>=0;i--)<br />printf("%d",a);<br />getch();<br />} - April 28, 2008 at 1:23 pm #3265Priyansh AgrawalParticipant
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:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152#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 />}
- AuthorPosts
Viewing 2 reply threads
- The forum ‘C Programming’ is closed to new topics and replies.