toByteArray

fun toByteArray(startIndex: Int = 0, endIndex: Int = size): ByteArray(source)

Returns a copy of subsequence starting at startIndex and ending at endIndex of a byte sequence wrapped by this byte string.

Parameters

startIndex

the start index (inclusive) of a subsequence to copy, 0 by default.

endIndex

the end index (exclusive) of a subsequence to copy, size be default.

Throws

when startIndex or endIndex is out of range of byte string indices.

when startIndex > endIndex.

Samples

import kotlinx.io.bytestring.*
import kotlin.test.*

fun main() { 
   //sampleStart 
   val string = ByteString(1, 2, 3, 4, 5)
val array = string.toByteArray()

assertContentEquals(byteArrayOf(1, 2, 3, 4, 5), array)

// Array is a copy of the byte string's content, so its modification won't affect the string.
for (idx in array.indices) {
    array[idx] = (array[idx] * 2).toByte()
}
assertEquals(ByteString(1, 2, 3, 4, 5), string) 
   //sampleEnd
}
import kotlinx.io.bytestring.*
import kotlin.test.*

fun main() { 
   //sampleStart 
   val string = ByteString(1, 2, 3, 4, 5)

assertContentEquals(byteArrayOf(2, 3, 4), string.toByteArray(startIndex = 1, endIndex = 4))
assertContentEquals(byteArrayOf(4, 5), string.toByteArray(startIndex = 3)) 
   //sampleEnd
}