Skip to main content
gamedev.net
🔒 Locked

String Number

Started by Axiverse 4 replies 700+ views
Original Post
Axiverse
Axiverse
What is the fastest way to convers numbers to strings? For integers? -Through Logerithems ( slow? ) -Through Mod? I have come up with the following, I don't know if it's any good...

PsuedoCode++:

char* result = new char [ ciel ( log ( abs ( value ))) + ( value >= 0 ) ? 1 : 2 ];

long start = abs ( value );
long diff = 0;
long end = 0;
int position = 0;

if ( value < 0 )
{
  result [ 0 ] = '-';
  position++;
}

Loop until start = 0

end = start / 10;
diff = start - end * 10;
result [ position++ ] =
start = end;

End Loop

result [ position ] = '\0';

For floats, double? -No idea at all...
Agony
Agony
If we interepret "fastest way" as "fastest way to program", I would suggest using the appropriate library functions, depending on language. In C, sprintf() (or better, snprint()/_snprintf()/whatever); in C++, std::stringstream; in [pick your language], [something].

In terms of algorithms, I don't know. You'll get faster speeds, certainly, if you leave out certain features, such as by only supporting integers, not caring about scientific notation, ignoring specific formatting options, etcetera. But really, when do you need to do so many number->string conversions in a short period of time that it's going to significantly affect the speed of a program? Probably not often.
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas nly, and not for things themselves." - John Locke o
Washu
Washu
Well, tbh, I can't think of any reason why you would have a lot of int->string conversions in a time intensive loop...but

Efficient Integer To String Conversions, part 2
Efficient Integer To String Conversions, part 3

and then there is the tried and true:

template<typename R, typename T>R lexical_cast(T const& t) {  std::ostringstream st;  R retval;  if(!(st<<t) || !(st>>r)) {    throw std::bad_cast((std::string("Unable to convert from ") + typeid(T).name() + " to " + typeid(R).name()).c_str());  }  return retval;}
In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.
iMalc
iMalc
If you're going to roll your own then don't even think about doing this:
char* result = new char [ ciel ( log ( abs ( value ))) + ( value >= 0 ) ? 1 : 2 ];
That's making things way too unnecessarily slow.

Just allocate enough space for the largest possible answer and be done with it. 12 bytes is pretty small anyway. Though you're actually better to have the caller provide a buffer to put the string into, like atoi, sprintf etc. That way you can avoid the alocation and chance of memory leaks altogether.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.