https://kotlinlang.org logo
Title
t

temp_man

10/03/2019, 6:44 PM
I need some help with parsing a ByteArray. I have a byte array that needs to be parsed to usable data. The instructions say to format it with "IEEE-754 32-bit floating point (little Endian)". It also says it has an offset of 0 and length of 4. I'm not sure where to start with this. I have tried a few options but the data is not close to what I expect.
s

streetsofboston

10/03/2019, 6:47 PM
For the JVM, you could use a
ByteBuffer
. Fill it with the bytes (eg wrap a ByteBuffer around a byte-array), then read in order using
ByteBuffer.getFloat()
.
t

temp_man

10/03/2019, 6:56 PM
Yeah I get that but I still have issues with the output. This may be on my end. Thanks
s

streetsofboston

10/03/2019, 6:57 PM
Kotlin’s spec doesn’t say anything about endian-ness. Have you tried modifying the incoming byte-array, swapping the byte-order of each set of 4 bytes?
t

temp_man

10/03/2019, 6:58 PM
How do you do that?
s

streetsofboston

10/03/2019, 6:58 PM
Just swap the order….
t

temp_man

10/03/2019, 7:00 PM
Holy shit! It worked
You are a Kotlin god
s

streetsofboston

10/03/2019, 7:01 PM
Well, thank you… 😄
Not sure on how many environments/targets you’d want to run this one; but for some you may need to swap the bytes, for others you don’t…..
t

temp_man

10/03/2019, 7:02 PM
I will look over the documentation and see what it calls for. Thanks again
It's for a bluetooth sensor
s

streetsofboston

10/03/2019, 7:04 PM
I guess the bluetooth sensor always returns the floats in little endian format. What about the client(s) reading the floats from the sensor, the code that will call
getFloat()
on the
ByteBuffer
?
E.g. most phones are little-endian. But you needed to swap the bytes to make it work, so i’m wondering on which client your kotlin code runs.
t

temp_man

10/03/2019, 8:39 PM
The clients should all returns the same thing right?
s

streetsofboston

10/03/2019, 8:45 PM
The
ByteBuffer.getFloat()
assumes a certain endian-ness. That can differ per platform/client. For phones, it is usually little-endianness, but that is not guaranteed. In your case, since you had to swap the bytes, it seems the platform assumed big-endianness
t

temp_man

10/03/2019, 8:46 PM
I had no idea different clients treated them differently.
s

streetsofboston

10/03/2019, 9:24 PM
@temp_man Instead of swapping the bytes yourself, i totally forgot you can force the endianness on your ByteBuffer: https://www.javamex.com/tutorials/io/nio_byte_order.shtml
1
t

temp_man

10/03/2019, 9:28 PM
You are right, just tried it and it worked as expected. I would imagine this would be a safer way to parse the array instead of calling reverse order.
:yes: 1
s

streetsofboston

10/03/2019, 9:35 PM
If you know what endianness your byte-array is, you can force the ByteBuffer to the same endianness. This removes any ambiguity and it is much less work for you (no extra swapping/parsing)! 🙂
👍 1