Go Down

Topic: String to int (Read 855 times) previous topic - next topic

philspitler

Hi, I found this code snipet for converting a string to an int, it works great with numbers up to 5 digits but after that it fails.

The code below will work but if I change viewCount to "123456" then my int become a negative number.

Any ideas?

Thanks.

Phil


Code: [Select]


viewCount="12345";
char this_char[viewCount.length() + 1];
viewCount.toCharArray(this_char, sizeof(this_char));
int newCount = atoi(this_char);
Serial.println(newCount);

FRiC

Maybe because int only goes up to 32767. Try using a long variable and the corresponding atol function.

AWOL

It's worth noting that the size (and therefore the range) of an "int" is platform-dependent; what works when compiled for a PC (which is what a lot of online examples will assume) may not work as expected when compiled for an Arduino.

On a PC, an "int" is typically four bytes long (32 bits) and represents the range -231 to 231-1, whereas on the Arduino, it is two bytes (16 its), and represents the range -215 to 215-1
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

michael_x

On an arduino, working with string instead of char* is already some overkill, IMO

char* viewCount="1234567";
long number = atol(viewCount);

should already work fine

AWOL

#4
May 02, 2012, 10:32 am Last Edit: May 02, 2012, 10:33 am by AWOL Reason: 1
Quote
working with string instead of char* is already some overkill,

Did you mean, "working with String instead of char* is already some overkill,"?
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Go Up