integer to string function (itoa())

Conor P. Cahill cpcahil at virtech.uucp
Sat Jun 30 23:55:54 AEST 1990


In article <1990Jun30.071229.23965 at agate.berkeley.edu> dankg at monsoon.Berkeley.EDU (Dan KoGai) writes:
>In article <153 at travis.csd.harris.com> brad at SSD.CSD.HARRIS.COM (Brad Appleton) writes:
>>In article <22888 at boulder.Colorado.EDU> baileyc at tramp.Colorado.EDU (BAILEY CHRISTOPHER R) writes:
>>
>>>Help, I need an itoa() function for use with my Sun compiler.
>>
>>Perhaps I missed something but ...  Is there some reason why:
>>
>	Maybe.  But I was wondering why there's no itoa() in most C libraries:
>atoi() exists and often used in scanf().  Why do we let [sf]printf() do
>all conversion instead of calling itoa...

When this was first posted, I was a bit skeptical about it.  A posting from
a university asking for a simple C routine that is presented in it's entirety
in K&R1 (pg 60).  I was inclined to believe this was for a class project.

Anyway, since people have already posted several solutions, here is mine (this
function will do binary, octal, decimal, and hexidecimal conversions, although
I have not modified it to handle negative numbers).  Have fun.


#!/bin/sh
# This is a shell archive (shar 3.21)
# made 06/30/1990 13:50 UTC by cpcahil at virtech
# Source directory /usr/local/src/lib/malloclib
#
# existing files WILL be overwritten
#
# This shar contains:
# length  mode       name
# ------ ---------- ------------------------------------------
#    491 -r--r--r-- tostring.h
#   2716 -r--r--r-- tostring.c
#
if touch 2>&1 | fgrep '[-amc]' > /dev/null
 then TOUCH=touch
 else TOUCH=true
fi
# ============= tostring.h ==============
echo "x - extracting tostring.h (Text)"
sed 's/^X//' << 'SHAR_EOF' > tostring.h &&
X/*
X * (c) Copyright 1990 Conor P. Cahill (uunet!virtech!cpcahil).  
X * You may copy, distribute, and use this software as long as this
X * copyright statement is not removed.
X */
X/*
X * $Id: tostring.h,v 1.2 90/05/11 00:13:11 cpcahil Exp $
X */
X#define B_BIN	 2
X#define B_DEC	10
X#define B_HEX	16
X#define B_OCTAL	 8
X
X/* 
X * $Log:	tostring.h,v $
X * Revision 1.2  90/05/11  00:13:11  cpcahil
X * added copyright statment
X * 
X * Revision 1.1  90/02/23  07:09:05  cpcahil
X * Initial revision
X * 
X */
SHAR_EOF
$TOUCH -am 0511001490 tostring.h &&
chmod 0444 tostring.h ||
echo "restore of tostring.h failed"
set `wc -c tostring.h`;Wc_c=$1
if test "$Wc_c" != "491"; then
	echo original size 491, current size $Wc_c
fi
# ============= tostring.c ==============
echo "x - extracting tostring.c (Text)"
sed 's/^X//' << 'SHAR_EOF' > tostring.c &&
X/*
X * (c) Copyright 1990 Conor P. Cahill (uunet!virtech!cpcahil).  
X * You may copy, distribute, and use this software as long as this
X * copyright statement is not removed.
X */
X#include "tostring.h"
X
X/*
X * Function:	tostring()
X *
X * Purpose:	to convert an integer to an ascii display string
X *
X * Arguments:	buf	- place to put the 
X *		val	- integer to convert
X *		len	- length of output field (0 if just enough to hold data)
X *		base	- base for number conversion (only works for base <= 16)
X *		fill	- fill char when len > # digits
X *
X * Returns:	length of string
X *
X * Narrative:	IF fill character is non-blank
X *		    Determine base
X *		        If base is HEX
X *		            add "0x" to begining of string
X *		        IF base is OCTAL
X *		            add "0" to begining of string
X *
X *		While value is greater than zero
X *		    use val % base as index into xlation str to get cur char
X *		    divide val by base
X *
X *		Determine fill-in length
X *
X *		Fill in fill chars
X *
X *		Copy in number
X *		
X *
X * Mod History:	
X *   90/01/24	cpcahil		Initial revision.
X */
X
X#ifndef lint
Xstatic
Xchar rcs_hdr[] = "$Id: tostring.c,v 1.4 90/05/11 00:13:11 cpcahil Exp $";
X#endif
X
X#define T_LEN 10
X
Xint
Xtostring(buf,val,len,base,fill)
X	int	  base;
X	char	* buf;
X	char	  fill;
X	int	  len;
X	int	  val;
X	
X{
X	char	* bufstart = buf;
X	int	  i = T_LEN;
X	char	* xbuf = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
X	char	  tbuf[T_LEN];
X
X	/*
X	 * if we are filling with non-blanks, make sure the
X	 * proper start string is added
X	 */
X	if( fill != ' ' )
X	{
X		switch(base)
X		{
X			case B_HEX:
X				*(buf++) = '0';
X				*(buf++) = 'x';
X				if( len )
X				{
X					len -= 2;
X				}
X				break;
X			case B_OCTAL:
X				*(buf++) = fill;
X				if( len )
X				{
X					len--;
X				}
X				break;
X			default:
X				break;
X		}
X	}
X
X	while( val > 0 )
X	{
X		tbuf[--i] = xbuf[val % base];
X		val = val / base;
X	}
X
X	if( len )
X	{
X		len -= (T_LEN - i);
X
X		if( len > 0 )
X		{
X			while(len-- > 0)
X			{
X				*(buf++) = fill;
X			}
X		}
X		else
X		{
X			/* 
X			 * string is too long so we must truncate
X			 * off some characters.  We do this the easiest
X			 * way by just incrementing i.  This means the
X			 * most significant digits are lost.
X			 */
X			while( len++ < 0 )
X			{
X				i++;
X			}
X		}
X	}
X
X	while( i < T_LEN )
X	{
X		*(buf++) = tbuf[i++];
X	}
X
X	return( (int) (buf - bufstart) );
X
X} /* tostring(... */
X
X/*
X * $Log:	tostring.c,v $
X * Revision 1.4  90/05/11  00:13:11  cpcahil
X * added copyright statment
X * 
X * Revision 1.3  90/02/24  21:50:33  cpcahil
X * lots of lint fixes
X * 
X * Revision 1.2  90/02/24  17:29:42  cpcahil
X * changed $Header to $Id so full path wouldnt be included as part of rcs 
X * id string
X * 
X * Revision 1.1  90/02/22  23:17:44  cpcahil
X * Initial revision
X * 
X */
SHAR_EOF
$TOUCH -am 0511001490 tostring.c &&
chmod 0444 tostring.c ||
echo "restore of tostring.c failed"
set `wc -c tostring.c`;Wc_c=$1
if test "$Wc_c" != "2716"; then
	echo original size 2716, current size $Wc_c
fi
exit 0
-- 
Conor P. Cahill            (703)430-9247        Virtual Technologies, Inc.,
uunet!virtech!cpcahil                           46030 Manekin Plaza, Suite 160
                                                Sterling, VA 22170 



More information about the Comp.lang.c mailing list