Convert Double to ByteArray or Array<Byte> Kotlin

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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() =      ByteArray.allocate(java.lang.Long.BYTES)              .put(java.lang.Double.doubleToLongBits(this))              .bytes() 

And the usage:

val bytes = double.bytes() 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!