Home Forums C Programming base conversion

Viewing 2 reply threads
  • Author
    Posts
    • #2024
      kenez
      Participant

      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

    • #3264
      yeswanth
      Participant

      A program to convert a decimal number to its equivalent binary number.

      #include 
      #include
      void main()
      {
      unsigned long dec;
      int a[25],c=0,i;
      clrscr();
      printf("nENTER A DECIMAL NUMBER: ");
      scanf("%lu",&dec);
      printf("n%lu IN BINARY FORMAT: ",dec);
      while(dec>0)
      {
      a[c]=dec%2;
      dec=dec/2;
      c++;
      }
      for(i=c-1;i>=0;i--)
      printf("%d",a);
      getch();
      }
    • #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;
      }
Viewing 2 reply threads
  • The forum ‘C Programming’ is closed to new topics and replies.