从流中读取一定量的字节有问题

问题描述 投票:0回答:1

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

        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-manipulation bit bit-shift
1个回答
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;
        }
© www.soinside.com 2019 - 2024. All rights reserved.