thespeedracer38

2017 SW Practical SET 1 Q1

Dec 4th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #define MAX_BUFFER_CAP 1024
  2. #include <string.h>
  3. #include <stdio.h>
  4.  
  5. void decToBin(int);
  6. void decToOct(int);
  7. void decToHex(int);
  8.  
  9. int main(void)
  10. {
  11.     int num, choice;char ch;
  12.     clrscr();
  13.     do
  14.     {
  15.         ch = 'N';
  16.         printf("\nEnter a number in base 10: ");
  17.         scanf("%d", &num);
  18.         printf("Which base do you want to convert it to?\n");
  19.         printf("Press 1 for Binary\n");
  20.         printf("Press 2 for Octal\n");
  21.         printf("Press 3 for Hexadecimal\n\n");
  22.         printf("Enter your choice: ");
  23.         scanf("%d", &choice);
  24.         switch(choice)
  25.         {
  26.             case 1: printf("%d in binary is ", num);
  27.                 decToBin(num);
  28.                 break;
  29.             case 2: printf("%d in octal is ", num);
  30.                 decToOct(num);
  31.                 break;
  32.             case 3: printf("%d in hexadecimal is ", num);
  33.                 decToHex(num);
  34.                 break;
  35.             default:printf("You entered a wrong choice! Please try again!");
  36.                 ch = 'Y';
  37.  
  38.         }
  39.         if(ch == 'N')
  40.         {
  41.             printf("\n\nDo you want to continue (Y/N)? ");
  42.             ch = getche();
  43.         }
  44.  
  45.     }
  46.     while(toupper(ch) == 'Y');
  47.     getch();
  48.     return 0;
  49. }
  50.  
  51. void decToBin(int num)
  52. {
  53.     char bin[MAX_BUFFER_CAP];
  54.     char temp[MAX_BUFFER_CAP] = "";
  55.     while(num > 0)
  56.     {
  57.         sprintf(bin, "%d%s", num%2, temp);
  58.         strcpy(temp, bin);
  59.         num /= 2;
  60.     }
  61.     printf("%s", bin);
  62. }
  63.  
  64. void decToOct(int num)
  65. {
  66.     char oct[MAX_BUFFER_CAP];
  67.     char temp[MAX_BUFFER_CAP] = "";
  68.     while(num > 0)
  69.     {
  70.         sprintf(oct, "%d%s", num%8, temp);
  71.         strcpy(temp, oct);
  72.         num /= 8;
  73.     }
  74.     printf("%s", oct);
  75. }
  76.  
  77. void decToHex(int num)
  78. {
  79.     char hex[MAX_BUFFER_CAP];
  80.     char temp[MAX_BUFFER_CAP] = "";
  81.     while(num > 0)
  82.     {
  83.         int dig = num%16;
  84.         char ch;
  85.         if(dig < 10)
  86.         {
  87.             ch = '0'+ dig;
  88.         }
  89.         else
  90.         {
  91.             ch = 'A' + (dig - 10);
  92.         }
  93.         sprintf(hex, "%c%s", ch, temp);
  94.         strcpy(temp, hex);
  95.         num /= 16;
  96.     }
  97.     printf("%s", hex);
  98. }
Add Comment
Please, Sign In to add comment