将Double转换为ByteArray或Array< Byte>科特林 [英] Convert Double to ByteArray or Array<Byte> Kotlin

查看:170
本文介绍了将Double转换为ByteArray或Array< Byte>科特林的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给予双重奖励

val double = 1.2345

如何将其转换为Kotlin ByteArray和/或Array<Byte>?

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

转换1.2345后其内容如下所示

Whose content would look like the following after converting 1.2345

00111111 11110011 11000000 10000011
00010010 01101110 10010111 10001101

在Java中,有一种解决方案涉及Double.doubleToLongBits()(java.lang.Double的静态方法),但是在Kotlin中,Double引用了Kotlin.Double,而在这种情况下则没有这种解决方案(或任何其他有用的解决方案) )方法.

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.

我不介意解决方案是否导致该文件无法访问Kotlin.Double. :)

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

推荐答案

您仍然可以使用Java Double的方法,尽管您必须使用完全限定的名称:

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)

然后在ByteArray >在Java中有效的任何方式,例如

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

(再次输入完整的限定名称)

然后您可以为此创建一个扩展功能:

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

以及用法:

val bytes = double.bytes()

这篇关于将Double转换为ByteArray或Array&lt; Byte&gt;科特林的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆