C Program for Number System Conversion




#include<stdio.h>
#include<string.h>
#include<ctype.h>

#include<math.h>
#include<stdlib.h>
char *strrev(char *);
char *convert(int , int );
int con(char *,int);
char lookuptable[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char result[100];

int  main()
{

 char str[100];
 char *p=str;
 int choice;

 while(1)
 {     

  printf("\n 1 decimal----binary\t 2 decimal----octa\n");
  printf("\n 3 decimal----hexa  \t 4 octa----binary\n");
  printf("\n 5 octa----decimal  \t 6 octa----hexa\n");
  printf("\n 7 hexa----binary   \t 8 hexa----decimal\n");
  printf("\n 9 hexa----octa     \t 10 BINARY----Decimal\n");
  printf("\n 11 binary----octa  \t 12 binary----hexa\n");
  printf("\b 13.exit\n");
  printf("\n enter your choice\n");

  scanf("%d",&choice);

  if(choice<=3)
   printf("\n enter a decimal number\n");
  if(choice<=6 && choice >3)
   printf("\n enter a octal number\n");
  if(choice <=9 && choice >6)
   printf("\n enter a hexa\n");
  if(choice<=12 && choice>9)
   printf("\n enter a binary no\n");
  if(choice==13)
   printf("exiting....");  
  else 
   scanf("%s",str);
   switch(choice)
   {
    case 1:
     printf(" BINARY: %s" ,convert(con(p,10),2));
     break;
    case 2:
     printf(" octal: %s" ,convert(con(p,10),8));
     break;
    case 3:
     printf(" octal: %s" ,convert(con(p,10),16));
     break;
    case 4:
     printf(" BINRY: %s" ,convert(con(p,8),2));
     break;
     case 5:
     printf(" BINARY: %s" ,convert(con(p,8),10));
     break;
     case 6:
     printf(" BINARY: %s" ,convert(con(p,8),16));
     break;
     case 7:
     printf(" BINARY: %s" ,convert(con(p,16),2));
     break;
     case 8:
     printf(" BINARY: %s" ,convert(con(p,16),10));
     break;
     case 9:
     printf(" BINARY: %s" ,convert(con(p,16),8));
     break;
    case 10:
     printf(" DECIMAAL: %s" ,convert(con(p,2),10));
     break;
    case 11:
     printf(" OCTAL: %s" ,convert(con(p,2),8));
     break;
    case 12:
     printf(" hexa: %s" ,convert(con(p,2),16));
     break;
    case 13:
     exit(0);
    default:
    printf("your choice is not currect\n");


   }
  
 

 }
 
 }


   char *convert(int num, int base)
   {
 char *r;
 int i=0;
 do
 {
  result[i++]=lookuptable[(num%base)];
  num=num/base;
 }
 while(num>=base);

 result[i]=lookuptable[num];
 result[++i]='\0';
r=strrev(result);

     return(r);

   }

int    con(char *p,int base)
    {
 char *temp=p;
 int i=0 ,j=0,dec=0;
 strrev(p);
 while(*temp!='\0')
 {
  if(islower(*temp))
  *temp=toupper(*temp);
  temp++;
 }

 while(*p!='\0')
 {
  while(lookuptable[i]!=(*p))
  i++;
  dec=dec+i* pow(base,j);
  j++;
  i=0;
  p++;
 }

 return(dec);
   }

char *strrev(char *str)
{
    int i = strlen(str) - 1, j = 0;

    char ch;
    while (i > j)
    {
        ch = str[i];
        str[i] = str[j];
        str[j] = ch;
        i--;
        j++;
    }
    return str;
}

Output

No comments:

Post a Comment