Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- avp 2011
- Convert long-long fixed integer (64-bit) to string in the specified radix
- (any 2..64 (bin, octal, decimal, hex ...) )
- Returns string length.
- */
- #ifdef TEST
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <limits.h>
- #endif
- int
- my_llstr (long long v, // source for 'printing'
- int radix,
- int unsign, // if 1 then unsigned source
- char *res) // memory for result
- {
- const char *dig = "0123456789abcdef";
- static const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- int rem[65], sp = 0; // stack for reminders
- char *p = res; // for return length
- unsigned long long u = v; // use if unsign == 1
- if (!res)
- return 0;
- if (radix < 2)
- radix = 2;
- if (radix > 64)
- radix = 64;
- if (radix > 16)
- dig = cb64;
- if (unsign) {
- while (u >= radix) {
- rem[sp++] = u%radix;
- u = u/radix;
- }
- // *res++ = (radix > 16)? cb64[u]: dig[u];
- *res++ = dig[u];
- } else {
- if (v < 0) {
- *res++ = '-';
- if (v == (1LL << 63)) {
- rem[sp++] = (unsigned long long)(1LL << 63) % radix;
- v = -(v / radix);
- } else
- v = -v;
- }
- while (v >= radix) {
- rem[sp++] = v%radix;
- v = v/radix;
- }
- // *res++ = (radix > 16)? cb64[v]: dig[v];
- *res++ = dig[v];
- }
- while (sp)
- // *res++ = (radix > 16)? cb64[rem[--sp]]: dig[rem[--sp]];
- *res++ = dig[rem[--sp]];
- *res = 0;
- return res-p;
- }
- #ifdef TEST
- main (int ac, char *av[])
- {
- long long x;
- int n;
- char buf[100];
- int r = av[1]? atoi(av[1]): 10;
- while (scanf("%lld",&x) == 1) {
- n = my_llstr(x, r, 0, buf);
- // buf[n] = 0;
- printf ("%s\n",buf);
- }
- my_llstr((1LL <<63), r, 0, buf);
- printf ("LLONG_MIN: %s (%lld)\n", buf, (1LL <<63));
- my_llstr((1LL <<63), r, 1, buf);
- printf ("unsigned LLONG_MIN: %s (%llu)\n",buf, (1LL <<63));
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement