Convert Double to ByteArray or Array<Byte> Kotlin

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()

It looks like some convinient methods were added since your answer and you can achieve the same with

val double = 1.2345
ByteBuffer.allocate(java.lang.Double.BYTES)
     .putDouble(double).array()

Tags:

Kotlin