Random.nextBytes所在位置是kotlin.random.Random.nextBytes,其相关用法介绍如下。

用法一

open fun nextBytes(
    array: ByteArray, 
    fromIndex: Int = 0, 
    toIndex: Int = array.size
): ByteArray
fun nextBytes(
    array: ByteArray, 
    fromIndex: Int, 
    toIndex: Int
): ByteArray

用随机字节填充指定字节array 的子范围,从fromIndex(含)开始,到toIndex(不包括)结束。

例子:

import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val bytes = ByteArray(4)
println(bytes.contentToString()) // [0, 0, 0, 0]

Random.nextBytes(bytes, 1, 3)
// second and third bytes are generated, rest unchanged
println(bytes.contentToString())

Random.nextBytes(bytes)
// all bytes are newly generated
println(bytes.contentToString())

val newBytes = Random.nextBytes(5)
// a new byte array filled with random values
println(newBytes.contentToString())
//sampleEnd
}

输出:

[0, 0, 0, 0]
[0, 106, 110, 0]
[-74, -76, -54, -100]
[-15, 35, -122, -115, -111]

返回array,子范围填充随机字节。

用法二

open fun nextBytes(array: ByteArray): ByteArray
fun nextBytes(array: ByteArray): ByteArray

用随机字节填充指定字节array并返回它。

例子:

import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val bytes = ByteArray(4)
println(bytes.contentToString()) // [0, 0, 0, 0]

Random.nextBytes(bytes, 1, 3)
// second and third bytes are generated, rest unchanged
println(bytes.contentToString())

Random.nextBytes(bytes)
// all bytes are newly generated
println(bytes.contentToString())

val newBytes = Random.nextBytes(5)
// a new byte array filled with random values
println(newBytes.contentToString())
//sampleEnd
}

输出:

[0, 0, 0, 0]
[0, 3, 114, 0]
[119, 20, -51, -122]
[114, -128, -32, -33, -88]

返回填充随机字节的array

用法三

open fun nextBytes(size: Int): ByteArray
fun nextBytes(size: Int): ByteArray

创建指定 size 的字节数组,填充随机字节。

例子:

import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val bytes = ByteArray(4)
println(bytes.contentToString()) // [0, 0, 0, 0]

Random.nextBytes(bytes, 1, 3)
// second and third bytes are generated, rest unchanged
println(bytes.contentToString())

Random.nextBytes(bytes)
// all bytes are newly generated
println(bytes.contentToString())

val newBytes = Random.nextBytes(5)
// a new byte array filled with random values
println(newBytes.contentToString())
//sampleEnd
}

输出:

[0, 0, 0, 0]
[0, -32, 0, 0]
[56, -66, -94, 122]
[73, -28, -40, 119, 49]