How about a method that converts a `String` to its...
# stdlib
a
How about a method that converts a
String
to its binary form (i.e 0s and 1s)
Copy code
fun main(args: Array<String>) {
    println("foo".binaryRepresentation())
}

fun String.binaryRepresentation(): String {
    val bytes = toByteArray()
    val binary = StringBuilder()
    for (b in bytes) {
        var save = b.toInt()
        for (i in 0 until Byte.SIZE_BITS) {
            binary.append(if (save and 128 == 0) 0 else 1)
            save = save shl 1
        }
        binary.append(' ')
    }
    return binary.toString()
}
I do not know if there is something in the stdlib that can do it though...
That is the output by the way
01100110 01101111 01101111
Or is there a simple way to do it
k
What's the use case?
a
None, just found it interesting... 🤷
k
But yeah there's a way easier solution, give me a sec.
fun String.binaryRepresentation() = toByteArray().joinToString(" ") { it.toString(2).padStart(8,'0') }
👍 1