Convert from BitArray to Byte

后端 未结 9 1630
再見小時候
再見小時候 2020-11-29 08:03

I have a BitArray with the length of 8, and I need a function to convert it to a byte. How to do it?

Specifically, I need a correct function of Co

9条回答
  •  时光说笑
    2020-11-29 08:41

    Unfortunately, the BitArray class is partially implemented in .Net Core class (UWP). For example BitArray class is unable to call the CopyTo() and Count() methods. I wrote this extension to fill the gap:

    public static IEnumerable ToBytes(this BitArray bits, bool MSB = false)
    {
        int bitCount = 7;
        int outByte = 0;
    
        foreach (bool bitValue in bits)
        {
            if (bitValue)
                outByte |= MSB ? 1 << bitCount : 1 << (7 - bitCount);
            if (bitCount == 0)
            {
                yield return (byte) outByte;
                bitCount = 8;
                outByte = 0;
            }
            bitCount--;
        }
        // Last partially decoded byte
        if (bitCount < 7)
            yield return (byte) outByte;
    }
    

    The method decodes the BitArray to a byte array using LSB (Less Significant Byte) logic. This is the same logic used by the BitArray class. Calling the method with the MSB parameter set on true will produce a MSB decoded byte sequence. In this case, remember that you maybe also need to reverse the final output byte collection.

提交回复
热议问题