从流中读取一定数量的位的问题

时间:2019-03-28 08:19:39

标签: c# bit-manipulation bit bit-shift

我有代码读取大小为1到8的位块。Homewer,它不能正常工作。

        private byte BitRead = 8;
        private ushort ValRead = 0;

        private byte[]  And = new byte[] { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF };
        private byte[] IAnd = new byte[] { 0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00 };

        public byte ReadBit(byte Bits)
        {
            Bit = 0;
            if (BitRead > 7)
            { 
                BitRead -= 8; 
                Bit = 0; 
                ValRead = (ushort)((ValRead << 8) | (byte)stream.ReadByte()); 
            }
            Bit = (byte)((ValRead >> (8 - BitRead - Bits)) & And[Bits]);
            BitRead += Bits;
            return Bit;
        }

例如,本节包含16个3位值:00 04 01 09 C4 D8

在正常情况下会是这样: 从我的代码: 0, 0, 0, 0, 2, 0, 0, 1, 0, 2, 3, 4, 2, 3, 3, 0 0, 0, 0, 0, 2, 0, 0, 1, 0, 2, 0, 4, 2, 0, 3, 0

16个5位值相同:84 1F 07 BD EE 73 9E F7 39 CE

正常情况: 我的代码: 16, 16, 15, 16, 15, 15, 15, 14, 14, 14, 15, 15, 14, 14, 14, 14 16, 0, 15, 0, 0, 15, 0, 14, 14, 0, 15, 0, 0, 14, 0, 14

1 个答案:

答案 0 :(得分:0)

最后我做到了。感谢PMF为我指出的问题。

        private byte Bit = 0;
        private byte BitRead = 0;
        private long ValRead = 0;

        private readonly byte[] And = new byte[] { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF };

        public byte ReadBit(byte Bits)
        {
            if (8 - BitRead - Bits < 0)
            {
                BitRead = (byte)-(8 - BitRead - Bits);
                ValRead = (ushort)((ValRead << 8) | (byte)stream.ReadByte());
                Bit = (byte)((ValRead >> 8 - BitRead) & And[Bits]);
            }
            else
            {
                Bit = (byte)((ValRead >> (8 - BitRead - Bits)) & And[Bits]);
                BitRead += Bits;
            }
            return Bit;
        }