I need some help with parsing a ByteArray. I have ...
# announcements
t
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
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
Yeah I get that but I still have issues with the output. This may be on my end. Thanks
s
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
How do you do that?
s
Just swap the order….
t
Holy shit! It worked
You are a Kotlin god
s
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
I will look over the documentation and see what it calls for. Thanks again
It's for a bluetooth sensor
s
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
The clients should all returns the same thing right?
s
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
I had no idea different clients treated them differently.
s
@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
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.
👌 1
s
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
141 Views