如何将bool[]转换为byte[]?

4

我有一个布尔数组:

bool[] b6=new bool[] {true, true, true, true, true, false, true, true,
                      true, false, true, false, true, true, false, false };

我如何将其转换为字节数组,使得:

  • byte[0]=0xFB
  • byte[1]=AC
  • 等等

4
请将布尔值转换为字节(C#) - Waqas
2
转换遵循哪些规则?您预计会得到多少字节的结果? - Oded
true 应该转换成什么?而 false 呢? - Emond
1
如果您在顶部右侧的搜索中找不到任何解决方案,请发布问题。 - Amar Palsapure
有符号的字节还是无符号的字节? - Huusom
5个回答

10

我认为你想要的是这样的:

static byte[] ToByteArray(bool[] input)
{
    if (input.Length % 8 != 0)
    {
        throw new ArgumentException("input");
    }
    byte[] ret = new byte[input.Length / 8];
    for (int i = 0; i < input.Length; i += 8)
    {
        int value = 0;
        for (int j = 0; j < 8; j++)
        {
            if (input[i + j])
            {
                value += 1 << (7 - j);
            }
        }
        ret[i / 8] = (byte) value;
    }
    return ret;
}

编辑:在明确要求之前的原始回答:

您并没有说明想要实现什么样的转换。例如,这个会起作用:

byte[] converted = Array.ConvertAll(b6, value => value ? (byte) 1 : (byte) 0);

或者类似地(但效率稍低)使用LINQ:

byte[] converted = b6.Select(value => value ? (byte) 1 : (byte) 0).ToArray();

之前不知道 Array.ConvertAll 这个方法。以为在使用 ConvertAll 之前必须调用 ToList(),所以对你的分享表示感谢 :) - Øyvind Bråthen
我想要得到位元1到位元8的结果。但是这段代码计算的是位元8到位元1的结果。 - Himanshu Bajpai
@HimanshuBajpai:如果一开始就给了明确的要求,我会满足它们的...但是更改上面的代码应该很容易。(提示:将value += 1 << j;这一行更改为使用不同的位移量进行移位即可...) - Jon Skeet
@HimanshuBajpai:我现在已经编辑了代码,主要是为了将来任何人来到这个问题时能够更好地理解。但是,下次您提问时,请从一开始就提供更多细节。阅读http://tinyurl.com/so-hints以获取有关如何提出问题的建议。 - Jon Skeet

7
如果你想将每个由八个布尔值组成的组转换成一个字节,你可以使用BitArray类:
byte[] data = new byte[2];
new BitArray(b6).CopyTo(data, 0);

数组data现在包含两个值0xDF和0x35。

编辑:

如果你想要结果为0xFB和0xAC,你需要先反转数组中的布尔值:

Array.Reverse(b6, 0, 8);
Array.Reverse(b6, 8, 8);

1
bytes = (from bit in b6 select bit ? (byte)1 : (byte)0).ToArray()

1
你可以使用 Linq 来实现这一点:
var byteArray = 
b6
.Select(b => (byte)(b ? 1 : 0))
.ToArray();

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接