crashhacker

emtime.c

Dec 21st, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #define usage() {printf("%s HH:MM\n", argv0); exit(1);}
  7.  
  8. const static char *argv0;
  9.  
  10. char *
  11. itoa_base(u_int64_t n, int base)
  12. {
  13.     char *res, *tab;
  14.     int i;
  15.  
  16.     if (n == 0)
  17.         return strdup("0");
  18.     tab = "0123456789abcdef";
  19.     res = calloc(65, 1);
  20.     i = 0;
  21.     if (res)
  22.     {
  23.         while (n > 0)
  24.         {
  25.             res[i++] = tab[n % base];
  26.             n /= base;
  27.         }
  28.         res[i] = 0;
  29.         int len = strlen(res);
  30.         for (int i = 0; i < len / 2; i++) {
  31.             char tmp = res[i];
  32.             res[i] = res[len-i-1];
  33.             res[len-i-1] = tmp;
  34.         }
  35.     }
  36.     return (res);
  37. }
  38.  
  39. void
  40. checkstr(const char *s)
  41. {
  42.     if (!isdigit(s[0])
  43.     || !isdigit(s[1])
  44.     || s[2] != ':'
  45.     || !isdigit(s[3])
  46.     || !isdigit(s[4])
  47.     || s[5] != 0)
  48.         usage();
  49. }
  50.  
  51. int
  52. maketime(const char *s)
  53. {
  54.     char num[3] = {0};
  55.     int minutes, hours;
  56.  
  57.     memmove(num, s, 2);
  58.     hours = atoi(num);
  59.     memmove(num, s+3, 2);
  60.     minutes = atoi(num);
  61.     return minutes + (hours * 60);
  62. }
  63.  
  64. int
  65. putemtime(int time)
  66. {
  67.     static int em_min, em_hr;
  68.     if (time >= 60) {
  69.         em_hr++;
  70.         return putemtime(time - 60);
  71.     }
  72.     if (time > 0) {
  73.         em_min++;
  74.         return putemtime(time - 1);
  75.     }
  76.     char *m = itoa_base(em_min, 6);
  77.     char *h = itoa_base(em_hr, 6);
  78.     printf("%s:%s\n", h, m);
  79.     return 0;
  80. }
  81.  
  82. int
  83. main(int argc, char **argv)
  84. {
  85.     static int time;
  86.     argv0 = argv[0]; // so we can have argv0 in usage
  87.  
  88.     if (argc != 2)
  89.         usage();
  90.     checkstr(argv[1]);
  91.     time = maketime(argv[1]);
  92.     time *= 1.5;
  93.     putemtime(time);
  94. }
Add Comment
Please, Sign In to add comment