Go Down

Topic: function to convert signed long to a scaled string (Read 367 times) previous topic - next topic

James-Brown

I need to convert a signed long received from a GPS module into a string that can be POSTed to a web site.  I have been working with a function like this:
Code: [Select]
// ScaleL4 will scale a long input by scale factor. Ex: ScaleL4( -1172483001,-7) = "-117.2483001"
String ScaleL4(long lonInput,int scale)
{
String strLeft;
String strRight;
String strIn ;
String strOut ;
strIn = "";

strIn += lonInput;
if (scale == 0)
{
strOut = strIn;
}

if (scale < 0)
{ // Scale smaller
int pos = (strIn.length() )+ scale;
strLeft = strIn.substring(0,pos);
strLeft += '.';
strRight = strIn.substring(pos);
strOut = strLeft +=strRight;
}
return strOut;
}

The code seems to work once or twice then blows up when called again.  The strOut returned has changed characters in it or becomes a huge String and destroys the sketch its running in.  The problem seems to be centered around the way the strRight is created.  A lot of the time the call to strIn.substring(pos) simply never returns.

I get the feeling that the String library is buggy. 
Am I right?

PaulS

Quote
I get the feeling that the String library is buggy. 
Am I right?

Yes, and no. It is not the String class itself that has problems. When a String instance goes out of scope, the destructor is called, which calls free() to deallocate the memory used. The free() function has a bug that corrupts the heap.

What you are doing with the String class can be done with division, dtostrf(), and char arrays.

johncc

Yes, String brings with it memory problems.

In another thread today I learned about dtostrf().  You could divide or multiply your value by 10^scale and then use dtostrf()?

Go Up