Convert Double to ByteArray or Array Kotlin

2019-04-25 19:17发布

问题:

Given a Double

val double = 1.2345

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

Whose content would look like the following after converting 1.2345

00111111 11110011 11000000 10000011
00010010 01101110 10010111 10001101

In Java, there is a sollution that involves Double.doubleToLongBits()(A static method of java.lang.Double), but in Kotlin, Double refers to Kotlin.Double, which has no such (or any other useful in this situation) method.

I don't mind if a sollution yields Kotlin.Double inaccessible in this file. :)

回答1:

You can still use Java Double's methods, though you will have to use full qualified names:

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

Then convert it to ByteArray in any way that works in Java, such as

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

(note the full qualified name again)


You can then make an extension function for this:

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

And the usage:

val bytes = double.bytes()


标签: kotlin