https://kotlinlang.org logo
m

martmists

09/26/2022, 6:12 PM
Does kotlin have something similar to
\xFF
escapes in strings? I can only find
\uFFFF
but this will likely create two bytes instead of one
e

ephemient

09/26/2022, 6:13 PM
like Java,
Char
is a 16-bit value
m

martmists

09/26/2022, 6:21 PM
Then what's the recommended way to create a UByteArray from a string? I currently have
Copy code
fun String.toUByteArray(): UByteArray {
    val chunks = chunked(2)
    val result = UByteArray(length) {
        chunks[it].toUByte(16)
    }
    return result
}
but ideally I could just use escapes so I could do
"somedata\x01\x02\x03"
instead of having to write everything as hex
e

ephemient

09/26/2022, 6:24 PM
on JVM, you could
Copy code
"somedata\u0001\u0002\u0003".toByteArray(Charsets.ISO_8859_1).asUByteArray()
and on multiplatform, you could
Copy code
"somedata\u0001\u0002\u0003".map { it.code.toUByte() }.toUByteArray()
but there isn't really a good ergonomic way to do this
or
UByteArray(string.length) { string[it].code.toUByte() }
to skip the intermediate
List
m

martmists

09/26/2022, 6:29 PM
so there's no shorthand for 1-byte characters like \xFF?
e

ephemient

09/26/2022, 6:33 PM
there are no one-byte characters
even
'a'
is a UTF-16 code unit
10 Views