Get individual characters from integer value
in Propeller 1
Hello everyone. I feel like this should be simple, but I do not know how to do this in spin.
A value is being sent via a serial port in the following format: "B12345," (I'm using the Extended fullduplex serial so , is the delimiter.)
I am then taking everything after the first character and converting it to an integer. So the integer will equal 12345. I need to split this integer into 5 different variables equaling 1, 2, 3, 4, & 5. How do I go about this?
Here's my code:
testVar is equaling 12345 so I know the conversion is working properly. I just need to get digit1, digit2, etc to equal 1, 2, 3, etc.
Thank you in advance.
A value is being sent via a serial port in the following format: "B12345," (I'm using the Extended fullduplex serial so , is the delimiter.)
I am then taking everything after the first character and converting it to an integer. So the integer will equal 12345. I need to split this integer into 5 different variables equaling 1, 2, 3, 4, & 5. How do I go about this?
Here's my code:
PUB readSerial | type, content, contentAdr, value, b
repeat
readBuffer := "0"
serial.rxflush
repeat until readBuffer <> "0"
serial.RxStr(@readBuffer)
type := readBuffer 'Take first character of string sent from computer to see type
content := readBuffer[1] 'Take everything after the first character to get content
contentAdr := @readBuffer[1]
if type == "A"
if content == "1"
winValue := 1
elseif content == "2"
winValue := 2
if type == "B"
value := 0 ' reset value
repeat
b := byte[contentAdr++] ' get digit from string
if ((b => "0") and (b =< "9")) ' if digit
value := value * 10 + (b - "0") ' update value
else
quit
testVar := value
if testVar == 12345
serial.str(string("matches/"))
else
serial.str(string("not a match/"))
update(@digit1, @digit2, @digit3, @digit4, @dp)
testVar is equaling 12345 so I know the conversion is working properly. I just need to get digit1, digit2, etc to equal 1, 2, 3, etc.
Thank you in advance.
Comments
Why not just subtract "0" (= 48) from all nonzero bytes in the string to get a string of 5 values of 0 to 9 and pass these bytes to your update function?
pub dec_value(p_str) : value | c repeat c := byte[p_str++] if ((c => "0") and (c =< "9")) value *= 10 value += (c - "0") else quit
i=1
digit = string-48
value = 10*value + digit
loop until your at the last character of string[]
testVar := value digit1 := byte[contentAdr - 6] - "0" digit2 := byte[contentAdr - 5] - "0" digit3 := byte[contentAdr - 4] - "0" digit4 := byte[contentAdr - 3] - "0" digit5 := byte[contentAdr - 2] - "0"
or you calculate the digits from the decimal value, this is more universally usable:testVar := value digit1 := value / 10000 // 10 digit2 := value / 1000 // 10 digit3 := value / 100 // 10 digit4 := value / 10 // 10 digit5 := value / 1 // 10
Andy
Thank you so much.. This worked great.