In Scala, I receive a UDP message, and end up with a DatagramPacket whose buffer has Array[Byte] containing the message. This message, which is all ASCII characters, is entirely fixed length fields, some of them numbers, other single characters or strings. What is the fastest way to parse these fields out of the message data?
As an example, suppose my message has the following format:
2 bytes - message type, either "AB" or "PQ" or "XY"
1 byte - status, either a, b, c, f, j, r, p or 6
4 bytes - a 4-character name
1 byte - sign for value 1, either space or "-"
6 bytes - integer value 1, in ASCII, with leading spaces, eg. " 1234"
1 byte - sign for value 2
6 bytes - decimal value 2
so a message could look like
ABjTst1 5467- 23.87
Message type "AB", status "j", name "Tst1", value 1 is 5467 and value 2 is -23.87
What I have done so far is get an array message: Array[Byte], and then take slices from it,
such as
val msgType= new String(message.slice(0, 2))
val status = message(2).toChar
val name = new String(message.slice(3, 7))
val val1Sign = message(7).toChar
val val1= (new String(message.slice(8, 14)).trim.toInt * (if (val1Sign == '-') -1 else 1))
val val2Sign = message(14).toChar
val val2= (new String(message.slice(15, 21)).trim.toFloat * (if (val2Sign == '-') -1 else 1))
Of course, reused functionality, like parsing a number, would normally go in a function.
This technique is straightforward, but is there a better way to be doing this if speed is important?