Convert Double to ByteArray or Array <Byte> Kotlin

Considering double

val double = 1.2345 

How can I convert this to a Kotlin ByteArray and / or Array<Byte> ?

Whose content will look like this after conversion 1.2345

 00111111 11110011 11000000 10000011 00010010 01101110 10010111 10001101 

There is a solution in Java that includes Double.doubleToLongBits() (the static method java.lang.Double), but in Kotlin Double refers to Kotlin.Double , which does not have one (or any other useful in this situation).

I do not mind if in the solution this question allows Kotlin.Double inaccessibility. :)

+7
source share
1 answer

You can still use Java Double methods, although you have to use full names:

 val double = 1.2345 val long = java.lang.Double.doubleToLongBits(double) 

Then convert it to ByteArray any way that works in Java , e.g.

 val bytes = ByteBuffer.allocate(java.lang.Long.BYTES).putLong(long).array() 

(pay attention to the full name)


Then you can make an extension function for this:

 fun Double.bytes() = ByteBuffer.allocate(java.lang.Long.BYTES) .putLong(java.lang.Double.doubleToLongBits(this)) .bytes() 

And use:

 val bytes = double.bytes() 
+14
source

Source: https://habr.com/ru/post/1242994/


All Articles