Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Native how to convert ByteArray to String?

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.

like image 267
Stepango Avatar asked Mar 24 '18 17:03

Stepango


2 Answers

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.

like image 73
Willi Mentzel Avatar answered Sep 30 '22 07:09

Willi Mentzel


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

like image 21
Sin Avatar answered Sep 30 '22 07:09

Sin