【问题标题】:ByteArray to Float in kotlinByteArray 在 kotlin 中浮动
【发布时间】:2017-10-19 10:07:03
【问题描述】:

我有一个代表浮点值的 4 字节数组。 由于 kotlin 缺少 Byte 的按位运算,我如何以最佳方式将其转换为浮点数?

【问题讨论】:

标签: arrays kotlin type-conversion


【解决方案1】:

您可以使用 Java NIO ByteBuffer,它具有 getFloat()getFloat(index) 函数:

val bytes = byteArrayOf(1, 2, 3, 4)

val buffer = ByteBuffer.wrap(bytes)
val float1 = buffer.getFloat()  // Uses current position and increments it by 4
val float2 = buffer.getFloat(0) // Uses specified position

【讨论】:

  • 如果你的 4 字节数组代表一个 Little Endian 浮点值,你必须添加 .order(ByteOrder.LITTLE_ENDIAN): val wrap = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
  • 三年后我仍在寻找答案。这个解决方案的问题在于它只是 Java,它不适用于 Kotlin Multiplatform。对此有什么想法吗?
  • 如果这对您不起作用,请查看float.toBits(),然后使用以下内容:new byte[] { (byte) (intBits >> 24), (byte) (intBits >> 16), (byte) (intBits >> 8), (byte) (intBits) }
猜你喜欢
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多