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

守給你的承諾、 提交于 2020-01-04 09:27:11

问题


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?


回答1:


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



回答2:


For whatever it's worth, you can convert a Byte to a BinaryString and then to sequence of Booleans with:

  val b1 : Byte = 7
  (0x100 + b1).toBinaryString.tail.map{ case '1' => true; case _ => false }

Results in: Vector(false, false, false, false, false, true, true, true)


And, you would go back (Booleans to Byte) with:

  val s1 = Vector(false, false, false, false, false, true, true, true)
  Integer.parseInt( s1.map{ case true => '1'; case false => '0' }.mkString, 2 ).toByte


来源:https://stackoverflow.com/questions/16267771/how-to-convert-a-seqbyte-into-an-arrayboolean-representing-each-bit-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!