Pages: [1]   Go Down
Author Topic: function to convert signed long to a scaled string  (Read 336 times)
0 Members and 1 Guest are viewing this topic.
Near San Diego
Offline Offline
Jr. Member
**
Karma: 1
Posts: 69
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
// 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?
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 634
Posts: 50234
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Temple, Texas
Offline Offline
Sr. Member
****
Karma: 14
Posts: 361
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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()?
Logged

Pages: [1]   Go Up
Jump to: