Last active
August 29, 2015 14:20
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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