itoa'd you so?

Levi Pearson levi at cold.org
Fri Sep 21 20:37:11 MDT 2007


Charles Curley <charlescurley at charlescurley.com> writes:
>
> Have we beaten this thing into the ground yet?

Not quite yet.  Try this one:

void itoa(int n, char s[]) {
  int i, sign;
  sign = n;
    
  i = 0;
  do {
    s[i++] = "0123456789"[abs(n % 10)];
  } while ( n /= 10 );
  if (sign < 0)
    s[i++] = '-';
    
  s[i] = '\0';
  reverse(s);
}

void reverse(char s[]) {
  int c, i, j;
  for ( i = 0, j = strlen(s)-1; i < j; i++, j--) {
    c = s[i];
    s[i] = s[j];
    s[j] = c;
  }
}

This is a modification of someone's modification to the version in the
K&R C book.  You'll find it works correctly for all ints, doesn't
behave badly when you pass it the same buffer several times without
clearing it first, is nice and compact and elegant, and is at least as
fast as yours.  Oh, and it doesn't rely on casting a char to an int,
so it's "type safe". ;)

                --Levi



More information about the PLUG mailing list