ByteArray在Kotlin中浮动 [英] ByteArray to Float in kotlin

查看:57
本文介绍了ByteArray在Kotlin中浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a 4 bytes array which represent a float value. Since kotlin lack of bitwise operations for Byte how can I convert it to float in most optimal way?

推荐答案

您可以使用Java NIO

You can use the Java NIO ByteBuffer, it has the getFloat() and getFloat(index) functions for that:

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

这篇关于ByteArray在Kotlin中浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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