Convert string to Long

Hello,

I d'like to convert two string value to Long int.

The two string are in fact two long number i receive separate by a semicolone through the serial port :

int ind1 = cmd.indexOf(';');
int ind2 = cmd.indexOf(';', ind1 + 1);
String part1 = cmd.substring(0, ind1);
String part2 = cmd.substring(ind1 + 1, ind2);

At the end I have two differentes strings (part1 and part2)

String.Toint works fine for value under 32 768 but if the value exceed this... I have a problem.

This is why i'm looking for a (String.Tolong) command that doesn't exist of course. :slight_smile:

Do you have any suggestions ?

Thank you.

Do you have any suggestions ?

Use strings (lowercase s) instead of Strings then you can use the atol() function.

String.Toint works fine for value under 32 768 but if the value exceed this... I have a problem.

The toInt() method is stupidly named, because it does NOT return an int. It returns a long.

If you have problems using toInt() with a String that contains the textual representation of a number larger than 32767, then the problem is in YOUR code.

I tried with differents value.

It works fine while i'm entering a value under 32 768.
Above this if I try to read the value I sent, I have a wrong value.

https://www.arduino.cc/en/Reference/Int

I'm using Arduino Uno, not a Due or Zero...

Above this if I try to read the value I sent, I have a wrong value.

So, fix your code. We can't see it, so we can't help.

I told you that my code works while i'm using 16 bits value.

This is why i'm requesting help to convert String to Long instead of Int

This is a limit of ATMega based core

"On the Arduino Uno (and other ATMega based boards) an int stores a 16-bit (2-byte) value."

I'll try this :

int ind1 = cmd.indexOf(';');
int ind2 = cmd.indexOf(';', ind1 + 1);
String part1 = cmd.substring(0, ind1);
String part2 = cmd.substring(ind1 + 1, ind2);

char P1[10];
char P2[10];

long p1;
long p2;

strcpy(P1, part1);
strcpy(P2, part2);

p1 = atol(P1);
p2 = atol(P2);

Visibly, strcpy try to convert "part1" instead of his value.

strcpy(P1, part1);

Can you use strcpy() to copy a String to a string ?

Can you use strcpy() to copy a String to a string ?

No.

OP: Where is your code that tries to use toInt() to convert a String to a long?

Hello

I found the solution,

long int p1 = part1.toInt();

It doesn't appear Logical at all, define a long variable and use toInt after...

thank you

1 Like

It doesn't appear Logical at all, define a long variable and use toInt after..

The toInt() function converts a String into an integer
A long variable is an integer variable

Sounds quite logical to me

As PaulS mentioned in #2, .toInt really should be .toLong