/* number.c : PUBLIC DOMAIN - Jon MAyo - August 24, 2006 * converts a number to a string with some formatting */ #include #include #define ITOA_UPPER 64 #define ITOA_ZEROLEAD 128 #define ITOA_LEFT 65536L /* left justify */ #define ITOA_SIGN 131072L /* display sign character */ #define ITOA_SPECIAL 262144L #define ITOA_WIDTH(w) (((w)&255)<<8) #define ITOA_RADIX(r) (((r)&63)) char *itoa_s(int n, char *buf, unsigned len, unsigned long flags_or_radix) { char tmp[sizeof n * CHAR_BIT]; /* you can use 8 instead of CHAR_BIT */ const char *digits = "0123456789abcdefghijklmnopqrstuvwxyz"; unsigned radix=flags_or_radix&63; int width=(flags_or_radix>>8)&255; unsigned i, negative; char *str; if(radix>36 || radix<2) return 0; if(flags_or_radix&ITOA_UPPER) { digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; flags_or_radix&=~ITOA_UPPER; /* clear */ } negative=n<0; if(negative) n=-n; i=0; do { tmp[i++]=digits[n%radix]; n/=radix; } while(n); str=buf; if(!(flags_or_radix&ITOA_LEFT) && !(flags_or_radix&ITOA_ZEROLEAD)) { while(width>i) { *str++=' '; width--; } } if(negative) { *str++='-'; width--; } else if(flags_or_radix&ITOA_SIGN) { *str++='+'; width--; } if(flags_or_radix&ITOA_ZEROLEAD) { while(width>i) { *str++='0'; width--; } } while(i-->0) { *str++=tmp[i]; width--; } if(flags_or_radix&ITOA_LEFT) { while(width--) { *str++=' '; } } *str=0; return buf; } #ifdef STAND_ALONE #include #include #define NR(x) (sizeof(x)/sizeof*(x)) int main(int argc, char **argv) { int n, i, j; char buf[256]; const unsigned test[] = {2, 8, 10, 16, 36}; for(i=1;i