Mohammad Elsayed
Mohammad Elsayed

Reputation: 2066

Convert Int, Short, UInt, ...etc to bytes or byte array in Kotlin

I am using java nio ByteBuffer in my project in Android with Kotlin, I need to convert all primitive types into bytes so that I can put them into the ByteBuffer, specially the Unsigned types because java nio does not support Unsigned types like UInt, UShort, ...etc. I know this kind of questions should have been asked before but I could not find it.

Upvotes: 0

Views: 2494

Answers (3)

Martin Vysny
Martin Vysny

Reputation: 3201

ByteBuffer supports putInt(), putLong() etc, so you can call buf.putInt(unsignedInt.toInt()). Alternatively use https://github.com/mvysny/kotlin-unsigned-jvm

Upvotes: 1

michael
michael

Reputation: 75

Here is an example for UInt and you may do same job to other type:

internal fun UInt.to4ByteArrayInBigEndian(): ByteArray =
    (3 downTo 0).map {
        (this shr (it * Byte.SIZE_BITS)).toByte()
    }.toByteArray()

Upvotes: 2

Buddhabhushan Naik
Buddhabhushan Naik

Reputation: 93

In Kotlin, you can try below extension functions:

println(12.toUInt())
println((-12).toUInt())
println(12.toUInt().toByte())
println((-12).toUInt().toByte())

Output:

I/System.out: 12
I/System.out: 4294967284
I/System.out: 12
I/System.out: -12

PS.: I have used only Integers here but there are extension functions for other data-types too.

Upvotes: -1

Related Questions