Search code examples
androidarrayskotlinbyteuint32

In Kotlin, whats the cleanest way to convert a Long to uint32 ByteArray and an Int to uint8?


fun longToByteArray(value: Long): ByteArray {
    val bytes = ByteArray(8)
    ByteBuffer.wrap(bytes).putLong(value)
    return Arrays.copyOfRange(bytes, 4, 8)
}

fun intToUInt8(value: Int): ByteArray {
    val bytes = ByteArray(4)
    ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).putInt(value and 0xff)
    var array = Arrays.copyOfRange(bytes, 0, 1)
    return array
}

I think these are the Kotlin equivalents of some Java ways, but I'm wondering if these approaches are correct/necessary in Kotlin.

Edit: Fixing examples per comments, also demonstrating changing byte order. Thank you for the feedback. I'm going to accept the answer that demonstrated how to do this without ByteBuffer.


Solution

  • I prefer not to use ByteBuffer because it adds a dependency to the JVM. Instead I use:

    fun longToUInt32ByteArray(value: Long): ByteArray {
        val bytes = ByteArray(4)
        bytes[3] = (value and 0xFFFF).toByte()
        bytes[2] = ((value ushr 8) and 0xFFFF).toByte()
        bytes[1] = ((value ushr 16) and 0xFFFF).toByte()
        bytes[0] = ((value ushr 24) and 0xFFFF).toByte()
        return bytes
    }