integer to string function (itoa())

Jeffrey P. Bakke bakke at plains.UUCP
Sun Jul 1 22:58:56 AEST 1990


In article <4700055 at m.cs.uiuc.edu> carroll at m.cs.uiuc.edu writes:
> 
> I got a number of requests for this, so here it is:
> (This code is taken out of Epoch, where it works just fine).
> .... CODE
> 
> Alan M. Carroll                Barbara/Marilyn in '92 :
> carroll at cs.uiuc.edu            + This time, why not choose the better halves?
> Epoch Development Team         
> CS Grad / U of Ill @ Urbana    ...{ucbvax,pur-ee,convex}!cs.uiuc.edu!carroll


I'm not sure if I'm jumping in on the middle of a discussion but I happened
to catch this post as I went by.   An alternate to this code is the
code implemented directly in K&R.  If the above code is part of a discussion
of alternate methods of the itoa function than K&Rs, ignore the following
code.


/* --------------------------------------
   Name:      IntString
   Function:  Converts a Long integer value to a string
   Call:      IntString(n,str);
   Returns:   void
   -------------------------------------- */
void IntString(n,str)
long n;
char *str;
{
  int i=0;
  long int sign;

  if ((sign = n) < 0) n =- n;
  do
    str[i++] = (n % 10) + '0';
  while (( n /= 10) > 0);
  if (sign < 0)
    str[i++] = '-';
  str[i] = '\0';
  Reverse(str);
}


/* --------------------------------------
   Name:      Reverse
   Function:  Reverse string
   Call:      Reverse(str);
   Returns:   void
   -------------------------------------- */
void Reverse(str)
char *str;
{
  int i,j;
  char c;

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


Jeffrey P. Bakke     | Internet: bakke at plains.NoDak.edu | "Life... don't talk
2550 15th Str S #23B | UUCP    : ...!uunet!plains!bakke |  to me about life..."
Fargo, ND  58105     | BITNET  : bakke at plains.bitnet    |    - Marvin the PA



More information about the Comp.lang.c mailing list