I have an application that receives data in binary form through Bluetooth. I read the data using inputstream from a bluetoothsocket to a byte[]. But I must parse all messages, because they must have a given format to be valid. All messages are in binary.
My solution was to convert the byte[] to a string and then split the string and parse all received messages.
An example of the data to parse:
0000000010000001
I should know that the first 8 zeros are the header and 10000001 the real data.
My idea was to create a string (from the byte[]) that represents -> 0000000010000001
using new String(byte[])
and then split the whole string in one byte and check the value, like:
string1 had 00000000
string2 had 10000001
I know that 8 zeros are the header, therefore string2 has the representation of the data.
My question is about the efficiency of this method. Is this the best method to do this in a mobile environment?
String manipulation for parsing binary data is quite inefficient in terms of speed, memory consumption and also puts quite some burden on the garbage collector – because you always generate new string objects and forget them immediately.
In Java you have several choices to do it better:
DataInputStream: is a wrapper for anInputStreamwhere you read bytes, shorts, longs, doubles, etc directly from the stream.ByteBuffersand “derived” types likeShortBuffer… these are good for bulkd data transfers and also for binary parsing.As long as your data is byte-aligned, these are easy ways to go. If that’s not the case – well, then better learn how to do bit-manipulation using operators like
&,|,~,<<,>>.My suggestion is that you stick to
DataInputStreamas long as possible.