Skip to content

Instantly share code, notes, and snippets.

@ochim
Last active June 19, 2019 07:53
Show Gist options
  • Select an option

  • Save ochim/5e2fc34cc031d26c7568f9cfbb8d6d1e to your computer and use it in GitHub Desktop.

Select an option

Save ochim/5e2fc34cc031d26c7568f9cfbb8d6d1e to your computer and use it in GitHub Desktop.
[java] String.getBytes => [kotlin] String.toByteArray

[java] String.getBytes => [kotlin] String.toByteArray

fun String.toByteArray(
charset: Charset = Charsets.UTF_8
): ByteArray

Encodes the contents of this string using the specified character set and returns the resulting byte array.

import kotlin.test.assertTrue

fun main(args: Array<String>) {
    val charset = Charsets.UTF_8
    val byteArray = "Hello".toByteArray(charset)
    println(byteArray.contentToString()) // [72, 101, 108, 108, 111]
    println(byteArray.toString(charset)) // Hello
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment