Come scrivere bit in un file?
Domanda
Come scrivere bit (non byte) in un file con c #, .net? Sono preety bloccato con esso.
Modifica : sto cercando un modo diverso di scrivere ogni 8 bit come byte
Soluzione
La quantità minima di dati che è possibile scrivere contemporaneamente è un byte.
Se è necessario scrivere singoli valori di bit. (Come ad esempio un formato binario che richiede un flag 1 bit, un numero intero a 3 bit e un numero intero a 4 bit); dovresti bufferizzare i singoli valori in memoria e scrivere nel file quando hai un intero byte da scrivere. (Per prestazioni, ha senso bufferizzare di più e scrivere blocchi più grandi nel file).
Altri suggerimenti
- Accumula i bit in un buffer (un singolo byte può essere qualificato come "buffer")
- Quando aggiungi un bit, sposta a sinistra il buffer e metti il ??nuovo bit nella posizione più bassa usando OR
- Quando il buffer è pieno, aggiungerlo al file
Dovrai usare i bitshift o l'aritmetica binaria, dato che puoi scrivere solo un byte alla volta, non singoli bit.
Ho fatto qualcosa del genere per emulare un BitsWriter.
private BitArray bitBuffer = new BitArray(new byte[65536]);
private int bitCount = 0;
// Write one int. In my code, this is a byte
public void write(int b)
{
BitArray bA = new BitArray((byte)b);
int[] pattern = new int[8];
writeBitArray(bA);
}
// Write one bit. In my code, this is a binary value, and the amount of times
public void write(int b, int len)
{
int[] pattern = new int[len];
BitArray bA = new BitArray(len);
for (int i = 0; i < len; i++)
{
bA.Set(i, (b == 1));
}
writeBitArray(bA);
}
private void writeBitArray(BitArray bA)
{
for (int i = 0; i < bA.Length; i++)
{
bitBuffer.Set(bitCount + i, bA[i]);
bitCount++;
}
if (bitCount % 8 == 0)
{
BitArray bitBufferWithLength = new BitArray(new byte[bitCount / 8]);
byte[] res = new byte[bitBuffer.Count / 8];
for (int i = 0; i < bitCount; i++)
{
bitBufferWithLength.Set(i, (bitBuffer[i]));
}
bitBuffer.CopyTo(res, 0);
bitCount = 0;
base.BaseStream.Write(res, 0, res.Length);
}
}