Skip to content

Instantly share code, notes, and snippets.

@maxdeliso
Last active August 29, 2015 14:20
Show Gist options
  • Save maxdeliso/5d21660fa05df572141f to your computer and use it in GitHub Desktop.
Save maxdeliso/5d21660fa05df572141f to your computer and use it in GitHub Desktop.
reads strings from stdin, converts them to bytes, converts that to bits, converts that to ascii, and prints out the result.
import scala.io.StdIn
object Bits{
def main(args: Array[String]): Unit = {
while(true) {
println(
prettyBits(
Option[String](StdIn.readLine) match {
case Some(str) => for {
by <- str.map(_.toByte)
bi <- toBits(by).reverse
} yield bi
case None => IndexedSeq[Boolean]()
}
)
)
}
}
/* returns bits of byte, from MSB to LSB */
def toBits(by: Byte): List[Boolean] = {
if(by == 0) {
List()
} else {
(by % 2 == 1) :: toBits((by / 2).toByte)
}
}
def prettyBits(xs: IndexedSeq[Boolean]): String = {
val combine = (s: String, b: Boolean) => (s + (if(b) "0" else "1"))
xs.foldLeft("")(combine)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment