Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active December 25, 2015 23:09
Show Gist options
  • Save davidallsopp/7054731 to your computer and use it in GitHub Desktop.
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).
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