如何将Seq [Byte]转换为表示Scala中每个位的Array [Boolean] [英] How to convert a Seq[Byte] into an Array[Boolean] representing each bit in Scala

查看:66
本文介绍了如何将Seq [Byte]转换为表示Scala中每个位的Array [Boolean]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好的方法将字节序列转换为Seq [Boolean],其中每个元素代表字节序列中的一位?

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?

我目前正在执行此操作,但是byte2Bools似乎有点沉重...

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)

}

也许真正的问题是:哪种更好的byte2Bools实现?

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

推荐答案

首先,不需要foldLeft中的累加器是可变的集合.

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) }

第二,您可以使用isBitSet映射初始序列.

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

这篇关于如何将Seq [Byte]转换为表示Scala中每个位的Array [Boolean]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆