PDA

View Full Version : Convert ASCII String into Integer



SailerMan
11-10-2006, 11:13 PM
I am using a Maxbotic Sonar the I have Choices of Output Serial, PWM or Analog. I used the PWM and now I'm attemping serial.

The data is Sent "R065\r"· 065 is the range in Inches.

I am reading the 065 into a short array and then Adding the Elements as so..
Repeat Index From 0 to 2
·· R[Index]=Serial.RX-48··· '<----- FORGOT TO SUBTRACT 48

Range:=R[0]*100+R[1]*10+R[2]

It works but I'm wondering if there Is·a better way to handle this?

Thanks,
Eric




Post Edited (SailerMan) : 11/10/2006 5:19:39 PM GMT

Mike Green
11-10-2006, 11:28 PM
If I understand your serial data, what you've posted can't work because the bytes are ASCII characters, not binary digits and you have to compensate for the extra $30 ("0") value. If you know you're going to receive a digit string terminated by a return, you can convert on the fly:



Range := 0
repeat until (d := Serial.RX) == $0D
Range := Range * 10 + (d - "0")

SailerMan
11-11-2006, 12:18 AM
Sorry for not being clear..You are totally correct in my code above.

This is closer to my actual code



If Serial.RX=="R"
Repeat Index from 0 to 2
R[Index]=Serial.RX-48

Range:= R[0]*100+R*10+R



I like your approach much better plus it helps me think outside of my little obscure box.

If I understand your code it looks like a SHL·for Decimal.. Sheesh why didn't I think of that... http://forums.parallax.com/images/smilies/smile.gif

Thanks for your help,
Eric

Post Edited (SailerMan) : 11/10/2006 5:26:40 PM GMT

Mike Green
11-11-2006, 02:05 AM
Yeah, the same logic works for any base (binary, hexadecimal, etc.)