Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary convert Int to Float in Kotlin

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.

like image 353
aschoerk Avatar asked Dec 20 '17 12:12

aschoerk


People also ask

How do you convert to float in Kotlin?

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.


1 Answers

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.

like image 108
Oliver Charlesworth Avatar answered Sep 29 '22 05:09

Oliver Charlesworth