简体   繁体   English

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

[英]How to convert a Byte to a Bitstring in Kotlin?

I have an ArrayList of Bytes.我有一个字节数组列表。 Firstly, when i print them i see integers?首先,当我打印它们时,我看到的是整数? And the second thing is, i want to convert each Byte to a Bitstring and add it to a new list of bitstrings.第二件事是,我想将每个字节转换为位串并将其添加到位串的新列表中。 How do i do that as there is no "i.toBitString"?由于没有“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()预处理()

You can convert to any base with this method, in your case this should work:您可以使用此方法转换为任何基础,在您的情况下,这应该有效:

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

here is the docs:这是文档:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将字节数组转换为图像 [kotlin] - How to convert byte array to image [kotlin] 如何将 Object 转换为 Kotlin 中的字节数组 - How to convert an Object into a byte array in Kotlin 如何在 Kotlin 1.4 中将双精度(或浮点)转换为字节(或短)? - How to convert Double (or Float) to Byte (or Short) in Kotlin 1.4? 在 Kotlin 中将字节数组转换为字符串 - Convert Byte Array to String in Kotlin 如何在Kotlin Multiplatform项目的iOS模块中将String转换为Byte Array? - How to convert String to Byte Array in iOS module of Kotlin Multiplatform project? 如何在 Kotlin 中将字节大小转换为人类可读的格式? - How to convert byte size into human readable format in Kotlin? 将 Double 转换为 ByteArray 或 Array<Byte> 科特林 - Convert Double to ByteArray or Array<Byte> Kotlin 使用 kotlin 将 html 内容转换为 PDF 字节数组 - Convert html content to PDF Byte Array with kotlin 如何将单字节字符集(非 ASCII)ByteArray 转换为 Kotlin UTF8 字符串(如何避免 ��?) - How to convert single-byte charset (non-ASCII) ByteArray into Kotlin UTF8 String (How to avoid ��?) 如何在Kotlin中将具有空终止符的字节数组转换为String? - How do I convert a byte array with null terminating character to a String in Kotlin?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM