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?
The simplest way to do so is using parseByte() method of Byte class in java. lang package. This method takes the string to be parsed and returns the byte type from it.
A Java byte is the same size as a byte in computer memory: it's 8 bits, and can hold values ranging from -128 to 127. Be careful when using byte, especially if there is the possibility of a number greater than 127 (or less than -128). There isn't a way to store a larger value into a byte: the program will overflow.
We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With