Spec-Zone.ru › Kotlin 2

encodeToByteArray

kotlin-stdlib/kotlin.text/encodeToByteArray

Требования к платформе и версии: Common (1.4), JS (1.4), JVM (1.4), Native (1.3), Wasm-JS (1.8), Wasm-WASI (1.8)

expect fun String.encodeToByteArray(): ByteArray

Кодирует эту строку в массив байтов в кодировке UTF-8.

Любая некорректная последовательность символов заменяется последовательностью байтов для замены.

Примеры

import kotlin.test.*

fun main() { 
   //sampleStart 
   val format = HexFormat { bytes { groupSeparator = " "; bytesPerGroup = 1 } }

// \u00a0 is a non-breaking space
val str = "Kòtlin\u00a02.1.255"

// The original string contains 14 characters, but some of them are represented with multiple UTF-8 code units
val byteArray = str.encodeToByteArray()
println(byteArray.toHexString(format)) // 4b c3 b2 74 6c 69 6e c2 a0 32 2e 31 2e 32 35 35

// Replacing all "wide" characters with some ASCII ones results in a byte sequence matching the length of the string
val byteArrayWithAsciiCharacters = str.replace("\u00a0", " ").replace("ò", "o").encodeToByteArray()
println(byteArrayWithAsciiCharacters.toHexString(format)) // 4b 6f 74 6c 69 6e 20 32 2e 31 2e 32 35 35

val byteArrayWithVersion = str.encodeToByteArray(startIndex = 7)
println(byteArrayWithVersion.toHexString(format)) // 32 2e 31 2e 32 35 35

val byteArrayWithoutTheVersion = str.encodeToByteArray(startIndex = 0, endIndex = 6)
println(byteArrayWithoutTheVersion.toHexString(format)) // 4b c3 b2 74 6c 69 6e 
   //sampleEnd
}

expect fun String.encodeToByteArray(startIndex: Int = 0, endIndex: Int = this.length, throwOnInvalidSequence: Boolean = false): ByteArray

Кодирует эту строку или её подстроку в массив байтов в кодировке UTF-8.

Параметры

startIndex

начало (включительно) кодируемой подстроки; по умолчанию — 0.

endIndex

конец (не включительно) кодируемой подстроки; по умолчанию — длина этой строки.

throwOnInvalidSequence

указывает, следует ли выбрасывать исключение при некорректной последовательности символов или заменять её.

Исключения

IndexOutOfBoundsException

если startIndex меньше нуля или endIndex превышает длину этой строки.

IllegalArgumentException

если startIndex больше endIndex.

CharacterCodingException

если эта строка содержит некорректную последовательность символов и throwOnInvalidSequence имеет значение true.

Примеры

import kotlin.test.*

fun main() { 
   //sampleStart 
   val format = HexFormat { bytes { groupSeparator = " "; bytesPerGroup = 1 } }

// \u00a0 is a non-breaking space
val str = "Kòtlin\u00a02.1.255"

// The original string contains 14 characters, but some of them are represented with multiple UTF-8 code units
val byteArray = str.encodeToByteArray()
println(byteArray.toHexString(format)) // 4b c3 b2 74 6c 69 6e c2 a0 32 2e 31 2e 32 35 35

// Replacing all "wide" characters with some ASCII ones results in a byte sequence matching the length of the string
val byteArrayWithAsciiCharacters = str.replace("\u00a0", " ").replace("ò", "o").encodeToByteArray()
println(byteArrayWithAsciiCharacters.toHexString(format)) // 4b 6f 74 6c 69 6e 20 32 2e 31 2e 32 35 35

val byteArrayWithVersion = str.encodeToByteArray(startIndex = 7)
println(byteArrayWithVersion.toHexString(format)) // 32 2e 31 2e 32 35 35

val byteArrayWithoutTheVersion = str.encodeToByteArray(startIndex = 0, endIndex = 6)
println(byteArrayWithoutTheVersion.toHexString(format)) // 4b c3 b2 74 6c 69 6e 
   //sampleEnd
}

© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/encode-to-byte-array.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API