首页 > 解决方案 > 从流中读取一定数量的位的问题

问题描述

我有读取大小从 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

标签: c#bit-manipulationbitbit-shift

解决方案


最后我做到了。感谢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;
        }

推荐阅读