【问题标题】:How to convert a Byte to a Bitstring in Kotlin?如何在 Kotlin 中将字节转换为位串?
【发布时间】:2020-09-06 18:12:08
【问题描述】:

我有一个字节数组列表。首先,当我打印它们时,我看到整数?第二件事是,我想将每个字节转换为位串并将其添加到位串的新列表中。由于没有“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?)}

    }

}

预处理()

【问题讨论】:

    标签: kotlin byte bitstring


    【解决方案1】:

    您可以使用此方法转换为任何基础,在您的情况下这应该有效:

    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2011-02-28
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多