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.
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
stringFromUtf8
's source code. –
Yen stringFromUtf8
in the referenced link (here: StringBuilder.kt). –
Cloth 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)
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
stringFromUtf8
's source code. –
Yen stringFromUtf8
in the referenced link (here: StringBuilder.kt). –
Cloth In my case this worked:
ByteArray.decodeToString()
ByteArray.toString(Charsets.UTF_8)
ByteArray.commonToUtf8String()
They all gave the same result.
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.
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)
© 2022 - 2024 — McMap. All rights reserved.