Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 918
A.Sanchez.SD Avatar asked Aug 01 '18 22:08

A.Sanchez.SD


1 Answers

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
}
like image 134
Alexander Egger Avatar answered Sep 17 '22 14:09

Alexander Egger