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.

- 27,862
- 20
- 113
- 121

- 4,721
- 3
- 31
- 44
-
What is the encoding that was used to convert chars to bytes in that array? – Ilya Mar 25 '18 at 20:06
5 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.

- 27,862
- 20
- 113
- 121
It seems that this API has changed
Now just use this: string.toUtf8(start, end)
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

- 316
- 2
- 4
-
2Thanks to @Willi Mentzel for adding the reference for`stringFromUtf8`'s source code. – Sin Mar 25 '18 at 08:30
-
Very thanks. But I can't find the source of `stringFromUtf8` in the referenced link ([here: StringBuilder.kt](https://github.com/JetBrains/kotlin-native/blob/master/runtime/src/main/kotlin/kotlin/text/StringBuilder.kt)). – Mir-Ismaili Feb 11 '19 at 01:06
-
This API has been deprecated......ReplaceWith("string.toUtf8(start, end)" https://github.com/JetBrains/kotlin-native/commit/cba7319e982ed9ba2dceb517a481cb54ed1b9352#diff-45a5f8d37067266e27b76d1b68f01173 – Sin Feb 15 '19 at 09:01
-
The question was about converting ByteArray to String? How string.toUtf8(start, end) could help me? – kilg Sep 30 '21 at 12:02
In my case this worked:
ByteArray.decodeToString()
ByteArray.toString(Charsets.UTF_8)
ByteArray.commonToUtf8String()
They all gave the same result.

- 176
- 1
- 3
- 10
The OKIO library has a helper method for this commonToUtf8String
One can simply copy the method code don't need to add the entire lib just for this.

- 6,661
- 7
- 49
- 80
Another solution that could be used everyone but especially makes sense looking for a Kotlin Multiplatform solution and using ktor
library already is using io.ktor.utils.io.core.String
function directly without adding extra third pary library or extra actual class implementation. For example:
Your build.gradle.kts
for all platforms:
implementation("io.ktor:ktor-client-core:${Versions.ktor}")
implementation("io.ktor:ktor-client-android:${Versions.ktor}")
implementation("io.ktor:ktor-client-apache:${Versions.ktor}")
implementation("io.ktor:ktor-client-ios:${Versions.ktor}")
Then use it
io.ktor.utils.io.core.String(byteArray, offset, length, Charsets.UTF_8)

- 132
- 2
- 11