BinaryReader - 阅读单个“BIT”?

问题描述 投票:3回答:3

案件 : 再次尝试通过我的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;
    }

问题:

_BitArray [ Loop ] = Key . ReadBoolean ( );  

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

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

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

问候,

c# bitarray binaryreader binarystream
3个回答
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;
    }
}

2
投票

不,不可能将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线


1
投票

读取1个字节并使用位掩码将其转换为8个元素的bool数组

© www.soinside.com 2019 - 2024. All rights reserved.