BinaryReader - 阅读单个"BIT"?

Ahm*_*eim 3 c# bitarray binaryreader binarystream

案例:
再次尝试通过我的NIC捕获数据包,
我开发了2个Extensions用于捕获可变数量的位

    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;
    }
Run Code Online (Sandbox Code Playgroud)

问题:

_BitArray [ Loop ] = Key . ReadBoolean ( );  
Run Code Online (Sandbox Code Playgroud)

因为我正在尝试读取单个位,但是参考MSDN文档,
它将流位置提前1 BYTE而不是1 BIT!

从当前流中读取布尔值,并将流的当前位置前进一个字节.

问题:
我能真正捕获"仅"1位并将流位置提前1位吗?
请建议我解决方案或想法:)

问候,

Pav*_*ets 5

不,流定位基于byte步骤.您可以使用位定位编写自己的流实现.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在这里,添加了 bigEndian 支持 (2认同)
  • 更改方法签名以返回可为 null 的 bool,如果流返回 EOS (-1) 方法返回 null (2认同)