BinaryReader - Leggere un singolo "bit"?
-
13-11-2019 - |
Domanda
Case:
Di nuovo cercando di catturare i pacchetti attraverso la mia NIC,
Ho sviluppato 2 estensioni da utilizzare nel catturare il numero variabile di bit
.
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;
}
Problema:
.
_BitArray [ Loop ] = Key . ReadBoolean ( );
Come sto cercando di leggere i bit singoli, ma facendo riferimento a Documentazione MSDN ,
Avanza la posizione del flusso di 1 byte non 1 bit !!!
.legge un valore booleano dal flusso corrente e avanza la corrente Posizione del torrente di un Byte .
Domanda:
Posso davvero catturare "solo" 1 bit e avanzare la posizione del flusso di 1 bit?
Si prega di suggerirmi soluzioni o idee :)Saluti,
Soluzione
No, il posizionamento del flusso è basato sulla fase byte
.Puoi scrivere la propria implementazione del flusso con il posizionamento del bit.
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;
}
}
. Altri suggerimenti
No, non è possibile far avanzare un'istanza Stream
da un bit.La granularità più piccola I supporti del tipo Stream
è un byte
.
Potresti scrivere un wrapper attorno al Stream
che fornisce la granularità di un bit manipolando e memorizza nella cache del movimento di un unico byte.
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;
}
}
.
Nota: questo leggerà il byte dal lato destro in bit.Se volessi leggere da sinistra, è necessario modificare la linea return
un bit
Leggi 1 byte e convertirlo in 8-element bool array utilizzando maschere bit