Advertisement
skb50bd

Convert Numbers According to Base

Mar 20th, 2015
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.29 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<math.h>
  3. int main()
  4. {
  5.     int base, bin, oct, dec, hex, d, r, i;
  6.     printf("Enter Base: ");
  7. I:
  8.     scanf("%d",&base);
  9.     if(base!=2 && base!=8 && base!=10 && base!=16) //INVALID
  10.     {
  11.         printf("Error!!! Invalid Base!\n\nThe Base Should be: \n2 for Binary. or \n8 for Octal. or \n10 for Decimal or.\n16 for Hexadecimal\n\nEnter The Base Again: ");
  12.         goto I;
  13.     }
  14.     else if(base==2) //BINARY
  15.     {
  16.         printf("Enter The Binary Number: ");
  17.         scanf("%d",&bin);
  18.         dec=0, i=0;
  19.         while(bin!=0)
  20.         {
  21.             r=bin%10;
  22.             bin=bin/10;
  23.             dec=dec+(r*pow(2,i));
  24.             i++;
  25.         }
  26.         printf("The Corresponding Octal Value is: %o\n",dec);
  27.         printf("The Corresponding Decimal Value is: %d\n",dec);
  28.         printf("The Corresponding HexaDecimal Value is: %x\n",dec);
  29.  
  30.     }
  31.     else if(base==8) //OCTAL
  32.     {
  33.         printf("Enter The Octal Number: ");
  34.         scanf("%o",&oct);
  35.         dec=oct, i=1, bin=0;
  36.         while(dec!=0)
  37.         {
  38.             r=dec%2;
  39.             dec/=2;
  40.             bin+=r*i;
  41.             i*=10;
  42.         }
  43.         printf("The Corresponding Binary Value is: %d\n",bin);
  44.         printf("The Corresponding Decimal Value is: %d\n",oct);
  45.         printf("The Corresponding Hexadecimal Value is: %x\n",oct);
  46.     }
  47.     else if(base==10) //DECIMAL
  48.     {
  49.         printf("Enter The Decimal Number: ");
  50.         scanf("%d",&dec);
  51.         d=dec, i=1, bin=0;
  52.         while(d!=0)
  53.         {
  54.             r=d%2;
  55.             d/=2;
  56.             bin+=r*i;
  57.             i*=10;
  58.         }
  59.         printf("The Corresponding Binary Value is: %d\n",bin);
  60.         printf("The Corresponding Octal Value is: %o\n",dec);
  61.         printf("The Corresponding HexaDecimal Value is: %x\n",dec);
  62.     }
  63.     else if(base==16) //HEXADECIMAL
  64.     {
  65.         printf("Enter The Hexadecimal Number: ");
  66.         scanf("%x",&hex);
  67.         dec=hex, i=1, bin=0;
  68.         while(dec!=0)
  69.         {
  70.             r=dec%2;
  71.             dec/=2;
  72.             bin+=r*i;
  73.             i*=10;
  74.         }
  75.         printf("The Corresponding Binary Value is: %d\n",bin);
  76.         printf("The Corresponding Octal Value is: %o\n",hex);
  77.         printf("The Corresponding Decimal Value is: %d\n",hex);
  78.     }
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement