Reputation: 475
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?
Upvotes: 12
Views: 13656
Reputation: 434
I stumbled upon this and here is how I use it, if I am not mistaken this should be Kotlin Native 1.3:
fun to4ByteArray(value: Int): ByteArray {
return byteArrayOf(
value.toByte(),
(value shr 8).toByte(),
(value shr 16).toByte(),
(value shr 24).toByte(),
)
}
fun to4ByteArray(value: Float): ByteArray {
val bitRep = value.toRawBits()
return byteArrayOf(
bitRep.toByte(),
(bitRep shr 8).toByte(),
(bitRep shr 16).toByte(),
(bitRep shr 24).toByte(),
)
}
fun intFrom4ByteArray(value: ByteArray): Int {
if(value.size != 4) return 0
return (value[3].toInt() and 0xff shl 24) or
(value[2].toInt() and 0xff shl 16) or
(value[1].toInt() and 0xff shl 8) or
(value[0].toInt() and 0xff)
}
fun floatFrom4ByteArray(value: ByteArray): Float {
if(value.size != 4) return 0.0f
return Float.fromBits(
(value[3].toInt() and 0xff shl 24) or
(value[2].toInt() and 0xff shl 16) or
(value[1].toInt() and 0xff shl 8) or
(value[0].toInt() and 0xff)
)
}
Upvotes: 0
Reputation: 147941
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
Upvotes: 20