質問

ケース:
もう一度私の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ビットを1ビット撮影することができますか?
私に解決策やアイデアを提案してください:)

wantes、

役に立ちましたか?

解決

いいえ、ストリームの位置決めは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インスタンスを1ビットで進めることはできません。最小の粒度Streamタイプのサポートは1つのbyteです。

1バイトの移動を操作してキャッシュすることで、1ビットの粒度を提供する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 Lineをビットに変更する必要がある場合

1バイトを読み出して、ビットマスクを使用して8要素BOOLアレイに変換

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top