How can I write an efficient number to string routine?
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).
Related Questions
- I have set my SNMP write community string to a string value longer than 8 characters. How do I recover the string so that I can configure the unit using the Pro.11 configuration utility?
- How to write geometry Well-Known-Binary to hex-encoded string?
- How can I write an efficient number to string routine?