首页 > 解决方案 > 在 Kotlin 中将 Int、Short、UInt、...等转换为字节或字节数组

问题描述

我在我的带有 Kotlin 的 Android 项目中使用 java nio ByteBuffer,我需要将所有原始类型转换为字节,以便我可以将它们放入 ByteBuffer,特别是 Unsigned 类型,因为 java nio 不支持 Unsigned 类型,如 UInt、UShort、 ...ETC。我知道以前应该问过这类问题,但我找不到。

标签: androidkotlinnio

解决方案


在 Kotlin 中,您可以尝试以下扩展功能:

println(12.toUInt())
println((-12).toUInt())
println(12.toUInt().toByte())
println((-12).toUInt().toByte())

输出:

I/System.out: 12
I/System.out: 4294967284
I/System.out: 12
I/System.out: -12

PS.:我在这里只使用了整数,但也有其他数据类型的扩展函数。


推荐阅读