Last active
December 25, 2015 23:09
-
-
Save davidallsopp/7054731 to your computer and use it in GitHub Desktop.
Playing around with bytes and bits - based on a couple of forum threads on the Sept 2013 "Functional Programming Principles in Scala" MOOC on Coursera (progfun).
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
val bytes = List[Byte](0, 1, -1, 127, -128) | |
def toBits(b: Byte) = 0 to 7 map (b >> _ & 1) | |
val bits = bytes flatMap toBits | |
// Note: least-significant bit on the left! | |
// List(0, 0, 0, 0, 0, 0, 0, 0, | |
// 1, 0, 0, 0, 0, 0, 0, 0, | |
// 1, 1, 1, 1, 1, 1, 1, 1, | |
// 1, 1, 1, 1, 1, 1, 1, 0, | |
// 0, 0, 0, 0, 0, 0, 0, 1 | |
def bits2Byte(bs: Seq[Bit]): Int = bs.zipWithIndex.foldLeft(0) { case (acc, (b, i)) => acc | b << i }.toByte | |
def packBits(bs: Seq[Bit]) = bs.grouped(8).map(bits2Byte) | |
packBits(bits).toList | |
// List(0, 1, -1, 127, -128) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment