/* decimal.c : PUBLIC DOMAIN - Jon Mayo - August 11, 2006 * - You may remove any comments you wish, modify this code any way you wish, * and distribute any way you wish.*/ /* just in case you don't have sprintf/snprintf you can use this code. */ #include #include #include /* used to figure out how many digits we need */ static unsigned number_digits_10(unsigned long n) { /* this is a much better algorithm than this: * see p219 of Hacker's Delight, Henry S. Warren, Jr. * ISBN 0-201-91465-4 */ const unsigned long logtab[] = { /* not actually log10 for 0 */ 9, 99, 999, 9999, 99999UL, 999999UL, 9999999UL, 99999999UL, 999999999UL, #if ULONG_MAX > 9999999999 /* 64-bit support */ 9999999999ULL, 99999999999ULL, 999999999999ULL, 9999999999999ULL, 99999999999999ULL, 999999999999999ULL, 9999999999999999ULL, 99999999999999999ULL, 999999999999999999ULL, #endif ULONG_MAX, }; int i; for(i=0;;i++) { if(n<=logtab[i]) return i+1; } assert(1 /* should never get here */); return 0; } void decimal_to_str(unsigned long n, char *buf, size_t max) { unsigned i, len; /* comparing 10 table items is usually faster than other methods like * dividing or multiplying 10 times */ len=number_digits_10(n); assert(len+1 < max); /* overflow */ for(i=0;i #include /* just pass a list of filename to test this out on */ int main(int argc, char **argv) { unsigned long n; unsigned i; char buf[32]; for(i=1;i