Kotlin equivalent of Java's String.getBytes()
Asked Answered
M

1

45

In Java, you can convert a string into an array of its constituent bytes by calling myString.getBytes().

What's the equivalent of this in Kotlin?

Marxist answered 12/10, 2017 at 4:15 Comment(0)
S
68

Use the extension String.toByteArray() - which means you will write myString.toByteArray(). Note it defaults to UTF-8 encoding, but you can override this by providing an additional argument.

Squiggle answered 12/10, 2017 at 4:21 Comment(2)
Beware : Java's getBytes() can convert charsets (for example : myString.getBytes(Charsets.ISO_8859_1, Charsets.UTF_8) and if you want to keep this kind of conversion, you will need to use something like myString.toByteArray(Charsets.ISO_8859_1).toString(Charsets.UTF_8)Deci
This has been renamed to String.encodeToByteArray()Inchon

© 2022 - 2024 — McMap. All rights reserved.