https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
p

Philip Dukhov

01/13/2021, 1:17 AM
I need to convert
Int
to
ByteArray
.
.toByte()
gives only first 8 bits, but I need a whole number.
usePinned
looks like what I need, but it’s unreachable in the commonMain
👀 1
t

travis

01/13/2021, 1:23 AM
I'm using this to convert
Long
to
ByteArray
. Perhaps it could be adapted to your needs?
Copy code
private fun Long.toByteArray(): ByteArray {
    val data = ByteArray(8)
    var i = 0
    data[i++] = (this ushr 56 and 0xffL).toByte()
    data[i++] = (this ushr 48 and 0xffL).toByte()
    data[i++] = (this ushr 40 and 0xffL).toByte()
    data[i++] = (this ushr 32 and 0xffL).toByte()
    data[i++] = (this ushr 24 and 0xffL).toByte()
    data[i++] = (this ushr 16 and 0xffL).toByte()
    data[i++] = (this ushr  8 and 0xffL).toByte() // ktlint-disable no-multi-spaces
    data[i]   = (this         and 0xffL).toByte() // ktlint-disable no-multi-spaces
    return data
}
(adapted from Okio)
p

Philip Dukhov

01/13/2021, 2:20 AM
yeah, probably I need something like this, hoped there’s a built in way to do so, thanks
18 Views