13

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. :)

Caelum
  • 801
  • 2
  • 10
  • 19

2 Answers2

22

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()
hotkey
  • 140,743
  • 39
  • 371
  • 326
4

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()
firen
  • 1,384
  • 2
  • 14
  • 32