Serial binding - parse char to dec (solved)

Hello,

I have a serial binding working receiving data via COM port as string data.
The point is that my source is sendin bytes, in this special case 3 digit decimals which corresond to temperatures. 200 for example is 20.0 degrees.

What I did so far: split string to an array with my single chars (extended ASCII) representing my temperatures.
Is tehre anb easy way to get the decimal value (ASCII) out of the char?

I tried string.state.toString.getBytes(ASCII) already. This gives me values 256 below my wanted number…I could do some math on this now, bit hope for a more direct method.

Any help welcome.
Thanx in advance.

cal

If I had the String “200” and I needed to convert it to a float 20.0 using the following code:

val float temp = new Integer("200").intValue / 10.0

getBytes didn’t work because the byte encoding for the character “2” and the integer value of 2 are completely different.

NOTE: I did not verify I have the method names correct above. There may be a typo. Also, the decimal place on the 10.0 is required or else the parser will treat the result as an int even though it is being stored in a float.

Great…I’ll try your proposal and will report.

I managed in the meantime to parse the byte to the number… by having done this:

tempkbad = cc2.state.toString.get Bytes() //tempkbad as byte
tempdig = (((tempkbad.get(0))+256)/10.0) //tempdig as Number

Adding 256 was needed as the byte value did not report back the decimal code of the ASCII I use but a value reduced by 256.
So 20 degrees (dec code would be 200) which is a char in the extended ASCII (looks like “LL”) shows up as -56.

PS:
If you know how to get direcly from the char “LL” (dec code 200) to its decimal code, this would be perfect.

cal

This sort of low level bit and byte manipulation is more of the C/C++ way of processing data but IMHO counts as a code smell when done in Java or Xtend. Using the Integer class to parse the String is the more language appropriate way to convert from a String to a number. It handles all the edge cases, manages different encodings (e.g ASCII verses UTF-16) and requires fewer lines of code to accomplish. It will also generate an error if for some reason your socket returns something that isn’t a number.

That being said, I believe that the char primitive can be treated like a short, just as it can in C/C++ so you should just be able to use it as a number. I’m not positive about that though.

It worked as well, just minor changes were necessary:

var double tempdig0 = new Integer((temparray.get(0)).intValue+256)/10.0

Thanx again.