facebook like button

07 August, 2011

Program 71: Conversion to any base

The need:
    The program was given to me in my online quiz. Actually this is not the same program I made at that time. This is a modified one and I made it after 6 months of the quiz. This can also handle conversion of relatively large numbers.
The code:
----------------------------------------------------
/*base conversion from 10 to any base up to Z*/

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<conio.h>
double divide(double a,double b);
main()
   {char h;
do
{
 double k,m;
 int i=0,j,l;
 float str[100];
 char temp[100];
 printf("This is a program to convert decimal integers to any base less than 62\n");
 printf("'A' means 10 and so on. 'a' means 36 and so on\n");
 printf("\nEnter a decimal integer => ");
 scanf("%lf",&k);
 printf("Enter the base in which to be converted =>");
 scanf("%lf",&m);
 if(m==0)
 {
 printf("Please enter a natural number less than 36. program exiting..\n");
 exit(0);
 }
 while(k>0)
    {
 str[i]=fmod(k,m);
 k=divide(k,m);
 i++;
    } 
 l=i;
 j=l;
 for(i=0;j>=0;i++,j--)
  {
  if(str[i]<10)
  temp[j]= (int)str[i]+'0';
  else if(str[i]<36)
  temp[j]= (int)str[i]+'A'-10;
  else if(str[i]<62)
  temp[j]= (int)str[i]+'a'-36;
  if(m>61)
  {
  printf("base should be less than 62.\n");
  exit(1);
  }
  }
  printf("The conversion to base %.0f is => ",m);
 for(j=1;j<=l;j++)
printf("%c",temp[j]);
printf("\n\nWant to try more ? y/n");
fflush(stdin);
h=getchar();
}while(h=='y'||h=='Y');
printf("hit any key to continue...\n");
getche();
}
double divide(double a,double b)
{
 double d=0,e;
 for(e=1000000000000;e>=1;e/=10)
    {
    while(a>=e*b)
    {
  a-=e*b;
  d+=e;
 }
 } 
 return (d);
}


----------------------------------------------------


Remark:
  1. This program has a bug which is : "It works accurate upto 15digit numbers but it loses accuracy if the input number becomes larger than that." Try to find out.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply