0

I am creating an app that receives Bluetooth data. The data is then stored in an byte array in which will need to be converted to float but not all the data.

Here is an example of the byte array after it is converted to Hex:

36 32 35 2e 30 30 20 00 4e 52 33 31 34 2e 30 30 20 00 cb b7 

and that is 625.00 NR314.00 E

The values I need is 625.00 and 314.00

So basically 0 to 5th bytes, and 11 to 15th bytes since the array has a length of 20.

How am I able to traverse the byte array to grab the necessary bytes and then convert them to float?

*** Update1

This is the code I have so far, successfully able to convert the data and traverse the loop but now need to convert the data to float.

byte[] value = characteristic.getValue();
String decoded = new String(value, StandardCharsets.UTF_8);

char[] chars = decoded.toCharArray();
String numberString = "";
String numberString2 = "";
for(int i = 0; i < 6; i++){
    numberString += chars[i];
}
Float(numberString);

for(int i = 10; i < 16; i++){
    numberString2 += chars[i];
}
Float(numberString2);
Romko Smuk
  • 57
  • 10
  • 1
    Hint: Decode the byte array first then use a loop to iterate through the array and grab the number characters (0-9 and .) for example `for (int i = 0; i < byteArray.length; i++){if(yourLogicHere){numberString += byteArray[i];}}`, then cast it to a float when done `Float(numberString)` – sorifiend Apr 07 '21 at 00:57
  • What should I decode the byte array to? I was able to grab the necessary bytes from the byte array but is there a way to convert the byte array to ascii before looping through the array? – Romko Smuk Apr 07 '21 at 01:13
  • 1
    You could try `String decoded = new String(yourArray, StandardCharsets.UTF_8);` or something similar like https://stackoverflow.com/questions/28854837/byte-array-to-hex-char-array-conversion#28854932 – sorifiend Apr 07 '21 at 01:16
  • Casting to Float(numberString); does not work for me. I have updated the code above – Romko Smuk Apr 07 '21 at 02:01
  • 1
    Oh right, you need to use the full decleration like this `Float yourFloat = new Float(numberString);` or you can parse it like this `Float yourFloat = Float.parseFloat(numberString);` – sorifiend Apr 07 '21 at 02:03
  • I did that but still have an error, it claims that numberString is not an statement. The numberString stores char values – Romko Smuk Apr 07 '21 at 02:13
  • 1
    There must be more going on with your code that you didn't include in your edit. Both methods in my previous comment work with JDK15. – sorifiend Apr 07 '21 at 02:17
  • I used float instead of Float, I guess that makes the difference – Romko Smuk Apr 07 '21 at 02:19

0 Answers0