That function works, but programmatically, there are simpler ways, for example:
Code: Select all
char* longtostr( long zahl )
{
static char text[20]; //Make me static, otherwise it's on the stack and will screw up soon, if it's static, it's allocated always, but is not safe for multi-tasking/threading.
int loc=19;
text[19] = 0; //NULL terminate the string
while (zahl) //While we have something left, lets add a character to the string
{
--loc;
text[loc] = (zahl%10)+'0';
zahl/=10;
}
if (loc==19) //Nothing, lets at least put a 0 in there!
{
--loc;
text[loc] = '0';
}
return &text[loc]; //Start from where loc left off
}
Another solution is to take in an argument for an array + length, then try filling that in, this will make it safe for a multi-threaded environment
. So, something like this:
Code: Select all
void longtostr( long zahl , char *buffer, long max)
{
int tmp, size;
if (!zahl) //check for 0 first thing, assumes max>=2
{
buffer[0] = '0';
buffer[1] = 0;
return;
}
tmp= zahl; //Temporary
size = 0;
while (tmp) //Calculate the size of the string we require
{
tmp/=10;
++size;
}
if (size >= max-1) //Error, overflow, we assume max >= 5 :)
{
buffer[0] = 'O';
buffer[1] = 'v';
buffer[2] = 'f';
buffer[3] = 'l';
buffer[4] = 'w';
buffer[5] = 0;
}
buffer[size] = 0; //Set the size
while (zahl) //While we have something left, lets add a character to the string
{
--size;
buffer[size] = (zahl%10)+'0';
zahl/=10;
}
}
This second one isn't perfect, but much better, you can add checks for max == 0, or max==1 and return an error, or if an overflow condition happens, and max is <5, then you can return an error as well.
How this works:
zahl = 173
zahl % 10 = 3 (remainder of 173 / 10)
zahl / 10 = 17 (integer math)
zahl % 10 = 7
zahl / 10 = 1
zahl % 10 = 1
zahl / 10 = 0
While loops see's zahl = 0, and breaks, so when we placed 3,7,1 into our buffer backwards, forwards it is 173
. This works for any sized number, and is much more intuitive than checking each value, and is also multi-threading safe, since it can work on multiple arrays at a time.
--- Edit ---
Oops, fixed code tags... and code bug(s)