如何在Kotlin中将字节转换为位串?

问题描述

我有一个字节的ArrayList。首先,当我打印它们时,我看到整数吗?第二件事是,我想将每个字节转换为一个位串并将其添加到新的位串列表中。没有“ i.toBitString”,该怎么办?

fun preprocessing() {

    val userInput = readLine()
    val charset = Charsets.UTF_8
    val bytearray = userInput?.toByteArray()
    var bitsets = ArrayList<BitSet>()
    if (bytearray != null) {
       // for(i in bytearray){
        //    bitsets.add(i.toBitset?)}

    }

}

preprocessing()

解决方法

您可以使用此方法转换为任何库,在您的情况下,该方法应该起作用:

val userInput = "potatoes"
val bytearray = userInput.toByteArray(Charsets.UTF_8)
val bitsets = ArrayList<String>()

for (i in bytearray) {
    bitsets.add(i.toString(2))
}

bitsets.forEach { println(it) }

这是文档:

/**
 * Returns a string representation of this [Byte] value in the specified [radix].
 *
 * @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
 */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public actual inline fun Byte.toString(radix: Int): String = this.toInt().toString(checkRadix(radix))