Link to home
Start Free TrialLog in
Avatar of dhm
dhm

asked on

itoa function (not atoi)

I'm looking for a standard function to do integer-to-string conversion.  The comp.lang.c FAQ says to just use sprintf, but I'd rather live without that cruft.  I could swear I found just such a function once while browsing through man pages, but can't locate it again.
ASKER CERTIFIED SOLUTION
Avatar of msmits
msmits

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dhm
dhm

ASKER

Oops, I should've specified unix.  I guess I'll have to ask again.  Thanks for the reply.
After consulting a UNIX Sun Solaris system I came up with the following two from the atoi(3) man page:

  char *lltostr(long long value, char *ptr);
  char *ulltostr(unsigned long long value, char *ptr);

Otherwise a standard itoa is not very difficult:

  char *itoa(int val, char *ptr)
  {
    int sign = (val < 0) ? -1 : 1;
    char tmp[16];
    int i = 0, j = 0;

    val = sign * val;
    while (val != 0) {
      tmp[i] = (val % 10) + '0';
      val = val / 10;
      i++;
    }
    if (i == 0) {
      strcpy(ptr, "0");
    } else {
      if (sign == -1) {
        ptr[j] = '-';
        j++;
      }
      while (i != 0) {
        ptr[j] = tmp[i - 1];
        i--;
        j++;
      }
      ptr[j] = '\000';
    }
  }

While this may not be the most efficient solution or it may not even work, as I completely did this without a compiler and some test cases, it shows that the base-10 algorithm is not difficult.

Although I agree that a library function would be better, so you don't have to invent and test such trivial stuff...

Avatar of dhm

ASKER

Thanks for snooping around...I'd found the Solaris functions too, but they don't exist on the other platforms I compile for.  I ended up just writing itoa, ltoa, utoa, and ultoa:

const char *itoa( int n )
{
      static char buf[32]; /* yeech */
      sprintf( buf, "%d", n );
      return buf;
}

Now I've just gotta find out how to do thread-specific static
function data (on all those platforms).  *That* sort of thing is the hard part on library functions like this.  The logic is, as you say, trivial.
There are several solutions:
1. require the caller to pass a valid character buffer

2. malloc the space and require the caller to free it

I find the first solution the 'most' clean.