I have a 4 bytes array which represent a float value. Since kotlin lack of bitwise operations for Byte how can I convert it to float in most optimal way?
To convert a byte array to string in Kotlin, use String() constructor. String() constructor can take a Byte Array as argument and return a new string formed with the bytes in the given array.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
The second one is roughly equivalent to float[] arr2 = new float[12]; . By default, it sets all the values to 0, but you can customize that with FloatArray(12) { 1f } , where 1f can be any number you want to initialize all the items in the array as. You don't need that if you just want to set it to 0 though.
To create a Byte Array in Kotlin, use arrayOf() function. arrayOf() function creates an array of specified type and given elements.
You can use the Java NIO ByteBuffer
, it has the getFloat()
and getFloat(index)
functions for that:
val bytes = byteArrayOf(1, 2, 3, 4)
val buffer = ByteBuffer.wrap(bytes)
val float1 = buffer.getFloat() // Uses current position and increments it by 4
val float2 = buffer.getFloat(0) // Uses specified position
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