Kotlin Native how to convert ByteArray to String?

Stepango picture Stepango · Mar 24, 2018 · Viewed 12.2k times · Source

I was playing with the kotlin-native samples. I wonder how I could get String from pinned ByteArray. Just want to print it in the console.

Answer

Willi Mentzel picture Willi Mentzel · Mar 24, 2018

If you need a solution for the JVM, since stringFromUtf8 is only available for the native platform, use toString with a Charset as argument:

val byteArray = "Hello World".toByteArray(Charsets.UTF_8)   
val str = byteArray.toString(Charsets.UTF_8)

If you specifically only want to target native, use Sin's solution.