Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

How can I write an efficient number to string routine?

routine String write
0
Posted

How can I write an efficient number to string routine?

0

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

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123