Проблема с чтением определенного количества бит из потока - PullRequest
0 голосов
/ 28 марта 2019

У меня есть код, который читает блоки битов размером от 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 голосов
/ 28 марта 2019

Наконец я сделал это. Спасибо 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;
        }
...