Kotlin: UInt to ByteArray

Yuta SHIMAKAWA
1 min readMay 25, 2019

--

I wrote the story https://medium.com/@bananaumai/kotlin-convert-integers-into-bytearray-ca7a2bd9718a. Now, I remembered why I write such code. That is, UInt to ByteArray conversion.

What I wrote in above story same function is easily achieved by java.nio.ByteBuffer. It is like below.

val bufferSize = Int.SIZE_BYTES
val buffer = ByteBuffer.allocate(bufferSize)
buffer.order(ByteOrder.BIG_ENDIAN) // BIG_ENDIAN is default byte order, so it is not necessary.
buffer.putInt(n)

Because Java doesn’t have unsined integer types by nature, ByteBuffer or other Serialization library does not seems to have UInt support, it has became to an experimental functionality since Kotlin v1.3. Kotlin.Serialization seems to be still on the way of supporting it https://github.com/Kotlin/kotlinx.serialization/issues/310 .

So, the UInt to ByteArray conversion is like this.

--

--