| How can I write an efficient number to string routine?

Previous | Strings | Next

Q: | I am just curious how I can write my own and efficient IntToStr routine...

A:

Process the number starting from the end (i.e. from the least significant digit instead from the most significant digit), like in the following example, which is probably the most optimal code:

    char *IntToStr (unsigned long an_integer)
    {
      static char result [] = "          \0";    // 10 spaces and \0
      char *ptr = result + 10;
      while (an_integer)
        {
          *ptr-- = an_integer % 10 + '0';
          an_integer/=10;
        }
      return ptr;
    }

Note that `'static'` before char in the first line is essential: without it, the variable `'result'` will be allocated of the stack, so it will not live too long after this function returns. Returning any pointers which points to structures allocated on the stack is extremely dangerous (it is not only dangerous; it is almost completely nonsense, except if you performs some really nasty and bizzare hacks). The another solution (but less elegant) is to make `'result'` global (i.e. to define it out of the function).