Convert Byte Array to Bit Array?

前端 未结 6 1999
抹茶落季
抹茶落季 2020-12-30 20:43

How would I go about converting a bytearray to a bit array?

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 21:18

    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;
    }
    

提交回复
热议问题