I want to handle a value that has been read from file as 4 byte integer as if it was a 4 byte IEEE Float and convert it into such a variable. Are there any experiences, how this can be done in Kotlin in an easy and elegant way.
Convert String to Float in Kotlin/AndroidThe toFloat() method converts the string to a Float, It throws the NumberFormatException exception when the string is not a legitimate representation of a Float.
Use java.lang.Float.intBitsToFloat
. Note that this assumes a particular (though conventional) bit layout - see the docs for the inverse (floatToIntBits
) for details.
Example:
import java.lang.Float.intBitsToFloat
// ...
val x = 0x4D8EF3C2
println(intBitsToFloat(x)) // 2.99792448E8
Live demo.
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