【问题标题】:Convert Byte Array to Bit Array?将字节数组转换为位数组?
【发布时间】:2011-02-02 15:08:20
【问题描述】:

如何将字节数组转换为位数组?

【问题讨论】:

    标签: c# bit-manipulation


    【解决方案1】:

    显而易见的方式;使用接受字节数组的构造函数:

    BitArray bits = new BitArray(arrayOfBytes);
    

    【讨论】:

    • 如何处理预先存在的位数组?
    【解决方案2】:

    这取决于“位数组”的含义...如果您的意思是 BitArray 类的实例,Guffa 的答案应该可以正常工作。

    如果你真的想要一个位数组,例如bool[] 的形式,你可以这样做:

    byte[] bytes = ...
    bool[] bits = bytes.SelectMany(GetBits).ToArray();
    
    ...
    
    IEnumerable<bool> GetBits(byte b)
    {
        for(int i = 0; i < 8; i++)
        {
            yield return (b & 0x80) != 0;
            b *= 2;
        }
    }
    

    【讨论】:

    • 您的答案比上面的答案更合适,因为结果包含前导零。 +1
    【解决方案3】:
    public static byte[] ToByteArray(this BitArray bits)
     {
        int numBytes = bits.Count / 8;
        if (bits.Count % 8 != 0) numBytes++;
        byte[] bytes = new byte[numBytes];
        int byteIndex = 0, bitIndex = 0;
        for (int i = 0; i < bits.Count; i++) {
            if (bits[i])
                bytes[byteIndex] |= (byte)(1 << (7 - bitIndex));
            bitIndex++;
            if (bitIndex == 8) {
                bitIndex = 0;
                byteIndex++;
            }
        }
        return bytes;
    }
    

    【讨论】:

    • 只是好奇..他不想要这个功能吗?!!
    【解决方案4】:

    您可以使用BitArraybyte 数组创建位流。举个例子:

    string testMessage = "This is a test message";
    
    byte[] messageBytes = Encoding.ASCII.GetBytes(testMessage);
    
    BitArray messageBits = new BitArray(messageBytes);
    

    【讨论】:

      【解决方案5】:
      public static byte[] ToByteArray(bool[] byteArray)
      {
          return = byteArray
                     .Select(
                          (val1, idx1) => new { Index = idx1 / 8, Val = (byte)(val1 ? Math.Pow(2, idx1 % 8) : 0) }
                      )
                      .GroupBy(gb => gb.Index)
                      .Select(val2 => (byte)val2.Sum(s => (byte)s.Val))
                      .ToArray();
      }
      

      【讨论】:

        【解决方案6】:
        byte number  = 128;
        Convert.ToString(number, 2);
        

        => 输出:10000000

        【讨论】:

        • 您能否提供更多详细信息,说明您在做什么以及它是如何工作的?
        猜你喜欢
        • 2019-12-13
        • 1970-01-01
        • 2016-02-22
        • 2010-09-26
        • 2010-10-17
        • 2018-07-16
        • 1970-01-01
        • 2015-08-04
        相关资源
        最近更新 更多