itoa'd you so?

Levi Pearson levi at cold.org
Wed Sep 19 15:48:52 MDT 2007


Steve <smorrey at gmail.com> writes:

> But I think #1 was still an elegant answer, although maybe in an
> embedded situation it was less than optimal.
>
> I'll keep searching for a better solution, but my thinking was < code
> == less things to go wrong.

Here's an example for you, from http://www.jb.man.ac.uk/~slowe/cpp/itoa.html

char* itoa( int value, char* result, int base ) {
  // check that the base if valid
  if (base < 2 || base > 16) { *result = 0; return result; }

  char* out = result;
  int quotient = value;
      
  do {
    *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
    ++out;
    quotient /= base;
  } while ( quotient );

  // Only apply negative sign for base 10
  if ( value < 0 && base == 10) *out++ = '-';
  std::reverse( result, out );
  *out = 0;

  return result;
}

                --Levi



More information about the PLUG mailing list