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

1

6
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.

Kowtko answered 1/8, 2018 at 22:13 Comment(3)
myInt.toByte() and 0xFF.toByte() does not make much sense. myInt and 0xFF probably would, though. You do not want the result to be a Byte, as Byte is inherently signed.Cogitative
@LouisWasserman Thank you for reviewing and catching this Louis.Kowtko
It has to be val bytes = ByteArray(8)Prestidigitation
P
9

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
}
Prestidigitation answered 2/8, 2018 at 18:47 Comment(2)
why do you convert long to 4 bytes if long has 8 bytes in size in Java?Stenography
@DmitryKolesnikovich Looks like they're doing that for simplicity. Shifting it right 24 times gives you the highest word compared to getting the highest byte (though I'm sure you and others already know that) although I'm not sure how we're able to add a word to a byte array. It's all preference I guess and I'd recommend expanding it to include 24, 18, 16, 12, 8 and applying a bitmask of 0xFF instead of 0xFFFF in case anyone wants to operate on bytes instead of words. This way you get 8 bytes instead of 4 words.Pyo

© 2022 - 2024 — McMap. All rights reserved.