Advertisement
levartolona

C_PRG_LANG_EX_3.5

Feb 1st, 2020
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define ABS(n) n >= 0 ? n : -n
  5.  
  6. void reverse(char *s)
  7. {
  8.     int j = 0;
  9.     while (s[j])
  10.         j++;
  11.  
  12.     j--;
  13.     for(int i = 0; j > i; j--, i++)
  14.     {
  15.         char tmp = s[i];
  16.         s[i] = s[j];
  17.         s[j] = tmp;
  18.     }
  19.  
  20.     return;
  21. }
  22.  
  23. void itob(int n, char *s, int base)
  24. {
  25.     int sign = 0;
  26.     if (n < 0)
  27.         sign++;
  28.  
  29.     char *start = s;
  30.  
  31.     do
  32.     {
  33.         int curr_numb = n % base;
  34.         curr_numb = ABS(curr_numb);
  35.         switch (curr_numb)
  36.         {
  37.         case 10:
  38.             *s++ = 'A';
  39.             break;
  40.         case 11:
  41.             *s++ = 'B';
  42.             break;
  43.         case 12:
  44.             *s++ = 'C';
  45.             break;
  46.         case 13:
  47.             *s++ = 'D';
  48.             break;
  49.         case 14:
  50.             *s++ = 'E';
  51.             break;
  52.         case 15:
  53.             *s++ = 'F';
  54.             break;
  55.         default:
  56.             *s = curr_numb + '0';
  57.             s++;
  58.             break;
  59.         }
  60.  
  61.         n /= base;
  62.     } while (n);
  63.  
  64.     if (sign)
  65.         *s++ = '-';
  66.  
  67.     *s = '\0';
  68.  
  69.     reverse(start);
  70.  
  71.  
  72. }
  73.  
  74. int main(void)
  75. {
  76.     int numb = 1369;
  77.     char string[256];
  78.  
  79.     for (int base = 2; base <= 16; base++)
  80.     {
  81.         printf("\n\n\nBASE IS %i\n", base);
  82.         itob(numb, string, base);
  83.         printf("%i\n%s\n\n", numb, string);
  84.  
  85.         numb = 1;
  86.         itob(numb, string, base);
  87.         printf("%i\n%s\n\n", numb, string);
  88.  
  89.         numb = -1;
  90.         itob(numb, string, base);
  91.         printf("%i\n%s\n\n", numb, string);
  92.  
  93.         numb = -0;
  94.         itob(numb, string, base);
  95.         printf("%i\n%s\n\n", numb, string);
  96.  
  97.         numb = INT_MAX;
  98.         itob(numb, string, base);
  99.         printf("%i\n%s\n\n", numb, string);
  100.  
  101.         numb = INT_MIN;
  102.         itob(numb, string, base);
  103.         printf("%i\n%s\n\n", numb, string);
  104.     }
  105.  
  106.     return 0;
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement