integer to string function (itoa())

carroll at m.cs.uiuc.edu carroll at m.cs.uiuc.edu
Sun Jul 1 03:24:00 AEST 1990


I got a number of requests for this, so here it is:
(This code is taken out of Epoch, where it works just fine).
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
char *
UnsignedLongToString(n,base)
     unsigned long n;
     unsigned int base;
{
  char *digit = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  static char LongToStringBuffer[34];	/* 32+nul+negative sign */
  char *s = LongToStringBuffer + 33; /* at most 33 characters in binary */

  *s = 0;			/* terminate */
  while (n)			/* something there */
    {
    *--s = digit[n % base];		/* store bottom digit */
    n /= base;			/* shift right */
    }
  if (*s == 0) *--s = '0';		/* in case nothing was put in string */
  return s;
}

char *
LongToString(n,base)
     long n;
     int base;
{
  char *s;

  if (n < 0)
    {
      s = UnsignedLongToString((unsigned long) -n, base);
      *--s = '-';
    }
  else s = UnsignedLongToString((unsigned long) n, base);
  return s;
}
/* ------------------------------------------------------------------------ */
main()
{
  printf("%s\n",LongToString(-1234567,10));
  printf("%s\n",UnsignedLongToString(7654321,10));
  printf("%s\n",LongToString(0x12345,16));
}

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



More information about the Comp.lang.c mailing list