int to string by specified base
convert a int to string, by specified base, support 2 - 16,
code:
#include <stdio.h> /* * @author kuchaguangjie * @date 2012-04-03 22:10 * @mail kuchaguangjie@gmail.com */ /** * convert int to string of specified base, * @param n input number * @param s output string * @param base the base, between [2 - 16] * @param maxwidth the possible max width after convertion * @ return 0 means ok, -1 means has problem */ int itob_base(int n, char *s, int base, int maxwidth) { if(base>16 || base<2) { printf("base should between 2~16\n"); return -1; } int quotients[maxwidth], bc=0, i; while(n>=base) { quotients[bc++] = n % base; n /= base; } quotients[bc] = n; for(i=0;bc>=0;i++,bc--) { if(quotients[bc]<10) { s[i] = quotients[bc] + '0'; } else if(quotients[bc]<16) { s[i] = quotients[bc] + 'A' - 10; } } s[i] = '\0'; return 0; } /** * convert int to string of specified base, the possible max width is 32, * @param n input number * @param s output string * @param base the base, between [2 - 16] */ int itob(int n, char *s, int base) { return itob_base(n, s, base, 32); } main() { char s[33]; int n = 1000, base = 16; itob(n, s, base); printf("%s\n",s); }