Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ByteArray to Float in kotlin

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?

like image 536
user2186425 Avatar asked May 19 '17 10:05

user2186425


People also ask

How do you convert ByteArray to string in Kotlin?

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.

How do you convert ByteArray?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

How do I make a float array in Kotlin?

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.

How do you use ByteArray Kotlin?

To create a Byte Array in Kotlin, use arrayOf() function. arrayOf() function creates an array of specified type and given elements.


1 Answers

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
like image 165
hotkey Avatar answered Sep 21 '22 17:09

hotkey