Convert from BitArray to Byte

后端 未结 9 1634
再見小時候
再見小時候 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:31

    A poor man's solution:

    protected byte ConvertToByte(BitArray bits)
    {
        if (bits.Count != 8)
        {
            throw new ArgumentException("illegal number of bits");
        }
    
        byte b = 0;
        if (bits.Get(7)) b++;
        if (bits.Get(6)) b += 2;
        if (bits.Get(5)) b += 4;
        if (bits.Get(4)) b += 8;
        if (bits.Get(3)) b += 16;
        if (bits.Get(2)) b += 32;
        if (bits.Get(1)) b += 64;
        if (bits.Get(0)) b += 128;
        return b;
    }
    

提交回复
热议问题