Parsing Bytes Java Efficiently
byte, java, parsing, performance
Solution
ByteBuffer can handle this.
byte[] somebytes = { 1, 5, 5, 0, 1, 0, 5 };
ByteBuffer bb = ByteBuffer.wrap(somebytes);
int first = bb.getShort(); //pull off a 16 bit short (1, 5)
int second = bb.get(); //pull off the next byte (5)
int third = bb.getInt(); //pull off the next 32 bit int (0, 1, 0, 5)
System.out.println(first + " " + second + " " + third);
Output
261 5 65541
You can also pull off an arbitrary number of bytes using the `get(byte[] dst, int offset, int length)` method, and then convert the byte array to whatever data type you need.
Problem
so I am parsing a KNOWN amount of bytes. However, the first two bytes represent some number, then the next one represents a number that's only one byte, but then possibly the next four all represent one number that's large. Is there a better way to parse the data, other than the way I am. ``` switch (i) { //Status case 2: temp[3] = bytes[i]; break; case 3: temp[2] = bytes[i]; ret.put("Status", byteArrayToInt(temp).toString()); break; //Voltage case 4: temp[3] = bytes[i]; break; case 5: temp[2] = bytes[i]; ret.put("Voltage", byteArrayToInt(temp).toString()); break; //Lowest Device Signal case 6: temp[3] = bytes[i]; break; case 7: temp[2] = bytes[i]; ret.put("Lowest Device Signal", byteArrayToInt(temp).toString()); clearBytes(temp); break; ``` } I am looping through the array of bytes and I have a switch that knows which bytes go to which location, for example I know the 2nd and third bytes go to the Status code. So I take them and combine them into an int. the temp byte array is a byte[] temp = new byte[4]. Any better way to do this?