BinaryReader-读取单个"BIT"? [英] BinaryReader - Reading a Single " BIT "?

查看:149
本文介绍了BinaryReader-读取单个"BIT"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

问题:

_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.

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

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

此致

推荐答案

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

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

这篇关于BinaryReader-读取单个"BIT"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆