/*
 *			i t o a . c
 */

/*)LIBRARY
*/

#ifdef	DOCUMENTATION

title	itoa	Convert signed integer to Ascii
index		Convert signed integer to Ascii

synopsis
	.s.nf
	char *
	itoa(buffer, value)
	char	*buffer;	/* Where result goes	*/
	int	value;		/* Value to convert	*/
	.s.f
description

	itoa() converts a signed integer to its decimal Ascii
	representation, storing it in buffer.   Buffer will
	be null-terminated.  Itoa() returns a pointer to
	the null-terminator.

	Itoa() uses a division table, avoiding hardware division
	instructions and recursion. This makes it suitable as a
	model for implementation on small machines.

Author

	Martin Minow

Implementation

	You should #define INT_32 if integers occupy 32 bits.

#endif

/*
 * Note:	the largest positive 32 bit int is 2,147,483,647
 *		the largest positive 16 bit int is        32,767
 */

#define	FALSE	0
#define	TRUE	1
#define	EOS	0

static int power10[] = {
#ifdef	INT_32
	10000000,
	 1000000,
	  100000,
#endif
	   10000,
	    1000,
	     100,
	      10
};

#define	NPOWERS	((sizeof power10) / (sizeof (unsigned int)))


static
itoa(value, buffer)
register int		value;
register char		*buffer;
/*
 * Convert an unsigned number to ASCII
 */
{
	register unsigned int	*power;
	int			nonzero;

	if (value < 0) {
	    *buffer++ = '-';
	    value = -value;
	}
	power = power10;		/* Pointer to power table	*/
	nonzero = FALSE;		/* Don't output leading zeros	*/
	do {
	    for (*buffer = '0'; ((unsigned) value) >= *power; *buffer += 1)
		value -= *power;
	    if (*buffer != '0' || nonzero) {
		buffer++;
		nonzero = TRUE;
	    }
	} while  (++power < &power10[NPOWERS]);
	*buffer++ = (value + '0');	/* Digits place			*/
	*buffer = EOS;
	return (buffer);
}
