BinaryReader - Reading a Single “ BIT ”?

不打扰是莪最后的温柔 提交于 2019-12-07 17:31:35

问题


Case :
Again trying to capture packets through my NIC,
I have developed 2 Extensions to use in capturing variable number of bits

    public static string ReadBits ( this BinaryReader Key , int Value )
    {
        BitArray _BitArray = new BitArray ( Value );

        for ( int Loop = 0 ; Loop > Value ; Loop++ )
        {
/* Problem HERE ---> */   _BitArray [ Loop ] = Key . ReadBoolean ( );
        }

        return BitConverter . ToString ( _BitArray . ToByteArray ( ) );
    }

    public static byte [ ] ToByteArray ( this BitArray Key )
    {
        byte [ ] Value = new byte [ ( int ) Math . Ceiling ( ( double ) Key . Length / 8 ) ];
        Key . CopyTo ( Value , 0 );
        return Value;
    }

Problem :

_BitArray [ Loop ] = Key . ReadBoolean ( );  

As I'm trying to read single bits, but referring to MSDN Documentation,
It advances the stream position by 1 BYTE not 1 BIT !!!

Reads a Boolean value from the current stream and advances the current position of the stream by one byte.

Question :
Can I really capture "ONLY" 1 Bit & advance the stream position by 1 Bit ?
Please suggest me solutions or ideas :)

Regards,


回答1:


No, Stream positioning is based on byte step. You can write your own stream implementation with bit positioning.

class BitReader
{
    int _bit;
    byte _currentByte;
    Stream _stream;
    public BitReader(Stream stream)
    { _stream = stream; }

    public bool? ReadBit(bool bigEndian = false)
    {
      if (_bit == 8 ) 
      {

        var r = _stream.ReadByte();
        if (r== -1) return null;
        _bit = 0; 
        _currentByte  = (byte)r;
      }
      bool value;
      if (!bigEndian)
         value = (_currentByte & (1 << _bit)) > 0;
      else
         value = (_currentByte & (1 << (7-_bit))) > 0;

      _bit++;
      return value;
    }
}



回答2:


No it's not possible to advance a Stream instance by one bit. The smallest granularity the Stream type supports is one byte.

You could write a wrapper around Stream which provides the one bit granularity by manipulating and caching the one byte movement.

class BitStream { 
  private Stream _stream;
  private byte _current;
  private int _index = 8;


  public byte ReadBit() {
    if (_index >= 8) {
      _current = _stream.ReadByte();
      _index = 0;
    }
    return (_current >> _index++) & 0x1;
  }
}

Note: This will read the byte from the right side into bits. If you wanted to read from the left you'd need to change the return line a bit




回答3:


Read 1 byte and covert it to 8-element bool array using bit masks



来源:https://stackoverflow.com/questions/9455790/binaryreader-reading-a-single-bit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!