【问题标题】:How to get single byte out of BitArray (without byte[])?如何从 BitArray 中获取单个字节(没有字节 [])?
【发布时间】:2012-04-02 14:33:44
【问题描述】:

我想知道,有没有办法将 BitArray 转换为字节(与字节数组相反)?我将在 BitArray 中有 8 位..

 BitArray b = new BitArray(8);


//in this section of my code i manipulate some of the bits in the byte which my method was given. 

 byte[] bytes = new byte[1];
 b.CopyTo(bytes, 0);

这就是我到目前为止所拥有的......如果我必须将字节数组更改为字节或者我是否可以将 BitArray 直接更改为字节都没有关系。我希望能够将 BitArray 直接更改为一个字节......有什么想法吗?

【问题讨论】:

  • 对字节使用 BitArray 是没有意义的。只需使用 |和 & 运算符在一个字节上。
  • byte firstByte = bytes[0];? (最后一段似乎令人困惑。)
  • 我似乎无法完全使用 &。我正在使用位移来访问位并根据需要进行设置。设置后,我将其放入 BitArray。对我来说似乎是最容易理解的方法。如果你能用简洁的方式解释它,我肯定会改变我处理它的方式... PS。感谢 cmets/帮助

标签: c# .net


【解决方案1】:

你可以写一个扩展方法

    static Byte GetByte(this BitArray array)
    {
        Byte byt = 0;
        for (int i = 7; i >= 0; i--)
            byt = (byte)((byt << 1) | (array[i] ? 1 : 0));
        return byt;
    }

你可以这样使用它

        var array = new BitArray(8);
        array[0] = true;
        array[1] = false;
        array[2] = false;
        array[3] = true;

        Console.WriteLine(array.GetByte()); <---- prints 9

9 十进制 = 1001 二进制

【讨论】:

  • 谢谢,这就是我要找的:)
猜你喜欢
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多