itoa() routine source code - (nf)

utzoo!decvax!harpo!ihnp4!ixn5c!inuxc!pur-ee!davy utzoo!decvax!harpo!ihnp4!ixn5c!inuxc!pur-ee!davy
Tue Nov 23 01:26:27 AEST 1982


#N:pur-ee:15500005:000:1069
pur-ee!davy    Nov 23 00:39:00 1982

/*
 *	Due to popular demand, I am posting a copy of my itoa() routine.
 *	Be careful what you pass this routine, note that "n" is declared
 *	as a long.  This will really barf on an 11/70 when you hand it
 *	an int.....I suppose I could have made it a union, but I'm lazy...
 *
 * --Dave Curry
 * pur-ee!davy
 */
/*
 * itoa - converts an integer n to characters, represented in base base.  Any
 *	  base from 2-36 is legal.
 */

char *itoa(n, base)
long n;
short base;
{
	int i, j;
	long sign;
	static char s[100];

	if ((base < 2) || (base > 36))
		return(0);

	if ((sign = n) < 0)
		n = -n;

	i = 0;
	do {
		if (base <= 10)
			s[i++] = n % base + '0';
		else {
			j = n % base;
			if (j < 10)
				s[i++] = j + '0';
			else
				s[i++] = (j-10) + 'a';
		}
	} while ((n /= base) > 0);

	if (sign < 0)
		s[i++] = '-';

	s[i] = '\0';

	reverse(s);

	return(s);
}
reverse(s)
char *s;
{
	int c, i, j;

	for (i=0, j = strlen(s)-1; i < j; i++, j--) {
		c = s[i];
		s[i] = s[j];
		s[j] = c;
	}
}

/* --------- If you don't see this line, you're article got zapped --------- */




More information about the Comp.lang.c mailing list