Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Seq[Byte] into an Array[Boolean] representing each bit in Scala

Is there a better way to convert a sequence of Bytes into an Seq[Boolean] where each element represents a bit from the Byte sequence?

I'm currently doing this, but byte2Bools seems a little too heavy...

object Main extends App {

  private def byte2Bools(b: Byte) =
    (0 to 7).foldLeft(ArrayBuffer[Boolean]())((bs, i) => bs += isBitSet(b, i))

  private def isBitSet(byte: Byte, bit: Int) =
    ((byte >> bit) & 1) == 1

  val bytes = List[Byte](1, 2, 3)
  val bools = bytes.flatMap(b => byte2Bools(b))

  println(bools)

}

Perhaps the real question is: what's a better implementation of byte2Bools?

like image 819
Kevin Herron Avatar asked Mar 17 '26 01:03

Kevin Herron


1 Answers

First, accumulator in foldLeft is not necessary need to be a mutable collection.

def byte2Bools(b: Byte): Seq[Boolean] = 
  (0 to 7).foldLeft(Vector[Boolean]()) { (bs, i) => bs :+ isBitSet(b)(i) }

Second, you can just map initial sequence with isBitSet.

def byte2Bools(b: Byte): Seq[Boolean] =
  0 to 7 map isBitSet(b)

def isBitSet(byte: Byte)(bit: Int): Boolean =
  ((byte >> bit) & 1) == 1
like image 172
4e6 Avatar answered Mar 18 '26 15:03

4e6



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!