Advertisement
avp210159

llstr.c

Oct 17th, 2014
725
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1. /*
  2.   avp 2011
  3.  
  4.   Convert long-long fixed integer (64-bit) to string in the specified radix
  5.   (any 2..64 (bin, octal, decimal, hex ...) )
  6.   Returns string length.
  7.  */
  8.  
  9. #ifdef TEST
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <limits.h>
  14. #endif
  15.  
  16. int
  17. my_llstr (long long v, // source for 'printing'
  18.       int radix,
  19.       int unsign,  // if 1 then unsigned source
  20.       char *res)   // memory for result
  21. {
  22.   const char *dig = "0123456789abcdef";
  23.   static const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  24.   int          rem[65], sp = 0;   // stack for reminders
  25.   char        *p = res;           // for return length
  26.   unsigned long long   u = v;     // use if unsign == 1
  27.  
  28.   if (!res)
  29.     return 0;
  30.   if (radix < 2)
  31.     radix = 2;
  32.   if (radix > 64)
  33.     radix = 64;
  34.   if (radix > 16)
  35.     dig = cb64;
  36.  
  37.   if (unsign) {
  38.     while (u >= radix) {
  39.       rem[sp++] = u%radix;
  40.       u = u/radix;
  41.     }
  42.     //  *res++ = (radix > 16)? cb64[u]: dig[u];
  43.     *res++ = dig[u];
  44.   } else {
  45.     if (v < 0) {
  46.       *res++ = '-';
  47.       if (v == (1LL << 63)) {
  48.     rem[sp++] = (unsigned long long)(1LL << 63) % radix;
  49.     v = -(v / radix);
  50.       } else
  51.     v = -v;
  52.     }
  53.     while (v >= radix) {
  54.       rem[sp++] = v%radix;
  55.       v = v/radix;
  56.     }
  57.     //    *res++ =  (radix > 16)? cb64[v]: dig[v];
  58.     *res++ = dig[v];
  59.   }
  60.  
  61.   while (sp)
  62.     //    *res++ =  (radix > 16)? cb64[rem[--sp]]: dig[rem[--sp]];
  63.     *res++ = dig[rem[--sp]];
  64.   *res = 0;
  65.   return res-p;
  66. }
  67.  
  68. #ifdef TEST
  69. main (int ac, char *av[])
  70. {
  71.   long long x;
  72.   int  n;
  73.   char buf[100];
  74.   int r = av[1]? atoi(av[1]): 10;
  75.  
  76.   while (scanf("%lld",&x) == 1) {
  77.     n = my_llstr(x, r, 0, buf);
  78.     //    buf[n] = 0;
  79.     printf ("%s\n",buf);
  80.   }
  81.  
  82.   my_llstr((1LL <<63), r, 0, buf);
  83.   printf ("LLONG_MIN: %s (%lld)\n", buf, (1LL <<63));
  84.   my_llstr((1LL <<63), r, 1, buf);
  85.   printf ("unsigned LLONG_MIN: %s (%llu)\n",buf, (1LL <<63));
  86.  
  87. }
  88. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement