Convert from BitArray to Byte

后端 未结 9 1584
再見小時候
再見小時候 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<byte> 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.

    0 讨论(0)
  • 2020-11-29 08:52

    This should work:

    byte ConvertToByte(BitArray bits)
    {
        if (bits.Count != 8)
        {
            throw new ArgumentException("bits");
        }
        byte[] bytes = new byte[1];
        bits.CopyTo(bytes, 0);
        return bytes[0];
    }
    
    0 讨论(0)
  • 2020-11-29 08:53

    That's should be the ultimate one. Works with any length of array.

    private List<byte> BoolList2ByteList(List<bool> values)
        {
    
            List<byte> ret = new List<byte>();
            int count = 0;
            byte currentByte = 0;
    
            foreach (bool b in values) 
            {
    
                if (b) currentByte |= (byte)(1 << count);
                count++;
                if (count == 7) { ret.Add(currentByte); currentByte = 0; count = 0; };              
    
            }
    
            if (count < 7) ret.Add(currentByte);
    
            return ret;
    
        }
    
    0 讨论(0)
提交回复
热议问题