如何使用c#和.net将位(而非字节)写入文件?我在这方面遇到了一些困难。
编辑: 我正在寻找一种不仅仅是将每8个位写为一个字节的不同方法。
编辑: 我正在寻找一种不仅仅是将每8个位写为一个字节的不同方法。
每次可以写入的最小数据量是一个字节。
如果您需要写入单个位值(例如需要1位标志、3位整数和4位整数的二进制格式),则需要将单个值缓冲到内存中,并在拥有完整的字节时写入文件。(为了提高性能,最好缓冲更多数据并一次性写入较大的块到文件中)。
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);
}
}
你将不得不使用位移或二进制算术,因为你只能一次写入一个字节,而不能写入单个位。