Converting a String to Long in Processing

Hi guys.

I've done some research before posting this but can't get an answer that makes sense.

I'm using Processing 2.2.1 to read serial data from a Uno and write it to a file. All good so far, it's working as expected. The data supplied from the usb port "appears" numeric when read off the A/D converter 0-1023. But it's not really numeric, it's a string.

I can understand why because of "sensorValue = myPort.readString();" so I guess reading from the serial port is considered as a string in any programming language?.

Regardless, I need to convert it to numbers so I can do some basic math calculations.

Help would be appreciated.

Cheers.

so I guess reading from the serial port is considered as a string in any programming language?.

No. Reading from the serial port using readString() and expecting something other than a string hardly makes sense.

Regardless, I need to convert it to numbers so I can do some basic math calculations.

Why do you (think you) need to convert the string representation of a value between 0 and 1023 to a long?

Processing makes it simple to convert a string to an int.
https://www.processing.org/discourse/beta/num_1173249138.html

Ok thanks Paul,

Yes, I did realise readString() was going to return a string but there didn't appear to be any other option. According to the reference, read() returns a number between 0-255.

In fact, I will ultimately need to read 0-32767 (15 bit). I was under the impression that the type int was 0-255, therefore I thought I needed long. Although I have now read from the reference "Datatype for integers, numbers without a decimal point. Integers can be as large as 2,147,483,647 and as low as -2,147,483,648." ???

Which has now confused me even more.

Thanks for the link. So the code would look something like this?:

string sensorValue;
sensorValue = myPort.readString();
int sensorValueNumber = Integer.parseInt(sensorValue);
println(sensorValueNumber);

So the code would look something like this?:

Yes, but it looks weird separating the declaration of the variable from the valuation of the variable.

string sensorValue = myPort.readString();

looks better to me.

The name is lousy, though, since the "value" is a string.

string valStg = myPort.readString();
int sensorValue = Integer.parseInt(valStg);

is what I would do.

Ah yes - that does make it a cleaner.

Thanks for your help Paul, I'll try this out when I get home from work.

Cheers.

btw. forgot to ask: Is it correct that the int range is 2,147,483,647 and as low as -2,147,483,648?
I guess there's only one way to find out for sure :slight_smile: