下面是我看到的一个比较好的例子
/* itoa.c is a portable version of Microsoft C's iota(). Unlike the Microsoft
version of the function, this version will return (along with the ASCII ver-
sion of the number) the "0x" prefix in the case of hexadecimal and the "0"
prefix in the case of octal. Honestly, sprintf() could probably be used just
as or more effectively than this program. In fact, the program uses
sprintf() to format the number as a string. Nevertheless, this program will
likely preclude the need to rewrite code if, for instance, the programmer
needs to port a DOS C program compiled by Microsoft C to a UNIX platform.
Note the program will use only 16-bit integers. This program was completed
on 8 Mar 93 by Christopher R. Gardner, Warner Robins Air Logistics Center.
*/
char *itoa(int n, char *s, int b) /* where b is the numerical base */
{
int c;
switch(b)
{
case 10: /* decimal */
sprintf(s, "%d", n);
break;
case 16: /* hexadecimal */
sprintf(s, "%#x", n);
break;
case 8: /* octal */
sprintf(s, "%#o", n);
break;
case 2: /* binary */
for (c = 16 - 1; c >= 0; c--, n >>= 1)
s[c] = (01 & n) + '0';
s[16] = '\0';
break;
default:
printf("Run Time Error: itoa() base argument not allowed\n");
exit(2);
} return s;
}