Kotlin Native how to convert ByteArray to String?

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.


It seems that this API has changed

Now just use this: string.toUtf8(start, end)

https://github.com/JetBrains/kotlin-native/commit/cba7319e982ed9ba2dceb517a481cb54ed1b9352#diff-45a5f8d37067266e27b76d1b68f01173

Legacy version:

Use stringFromUtf8

/**
 * Converts an UTF-8 array into a [String]. Replaces invalid input sequences with a default character.
 */
fun ByteArray.stringFromUtf8(start: Int = 0, size: Int = this.size) : String =
        stringFromUtf8Impl(start, size)

See here.

And if the byteArray is like CPointer<ByteVar> by interoperating C APIs, pleace use .toKString() in Kotlin-Native