kotlinbytebitstring

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"?

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


Solution

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