个案 :
再次尝试通过我的NIC捕获数据包,
我已经开发了2个扩展,用于捕获可变位数

    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;
    }

问题 :

_BitArray [ Loop ] = Key . ReadBoolean ( );  

因为我试图读取单个位,但指的是 MSDN文档,
它将流位置提前1个字节而不是1位!!!

从当前流中读取布尔值并推进当前 流的位置由一 字节.

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

问候,

有帮助吗?

解决方案

否,流定位基于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;
    }
}
.

其他提示

不,不可能提前一个 Stream 实例一位。最小粒度 Stream 类型支持是一个 byte.

你可以写一个包装 Stream 它通过操作和缓存一个字节的移动来提供一个比特的粒度。

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;
  }
}

注:这将从右侧读取字节为位。如果你想从左边阅读,你需要改变 return 行位

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top