Converting Strings to Longs

Ok, I admit it, this one has me beat. I've googled and spent more than a few hours trying out ideas and I'm stumped. I've built a parser for a serial stream that takes name/value pairs. I need to convert the 'value' to longs (timestamp). I need a function that is defined as folows:

long convertString (String str);

I can then call it to covert my values if they are of type long

I've tried the atoi() function and I must be missing something. Trid strtol() and couldn't make that work either.

If anyone can help it would be much appreciated.

Regards

Mudgee

For arduino-0019 and followers:

//
// Illustration of a function to convert a String
// to a long int using the C library function atol()
// (Arduino version 19 and successors)
//
// </begin Editorial>
// Why (oh why) didn't they just put something like the following
// in WString.h?
//
//
//      const char * c_str() const {return _buffer;}
//
//
// Then the main program could have done something like the following
//
//    long x = strtol(str.c_str(), NULL, 10);
//
// </end Editorial>
//
//  davekw7x
//

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    String str("-12345678");
    Serial.print("The string   : ");
    Serial.println(str);
    
    long x = stringToLong(str);
    Serial.print("The long int : ");
    Serial.println(x);
    Serial.println();
    delay(1000);
}

//
// I would have preferred the argument to be (const String & s)
// but that would be inconsistent with the lame definition of
// toCharArray in WString.h
//
// It also would have required the prototype to be in a separate
// header, since the Arduino prototype collector doesn't
// work with arguments that are references.
//
// Oh, well...
//
//  davekw7x
//
long stringToLong(String s)
{
    char arr[12];
    s.toCharArray(arr, sizeof(arr));
    return atol(arr);
}

Output:


T

he string   : -12345678
The long int : -12345678

Note that a "better" function might have some kind of error checking, using that feature of strtol (or even using something other than strtol).

Anyhow, this might be a start.

Regards,

Dave

Thanks Dave - this works a treat. Very much appreciated. Now I can get on with the rest of the project.

Cheers :slight_smile: