4

如何使用 c#、.net 将位(而不是字节)写入文件?我很喜欢它。
编辑:我正在寻找一种不同的方式,将每 8 位写入一个字节

4

4 回答 4

6

您一次可以写入的最小数据量是一个字节。

如果您需要写入单个位值。(例如需要 1 位标志、3 位整数和 4 位整数的二进制格式);当您有一个完整的字节要写入时,您需要在内存中缓冲各个值并写入文件。(为了性能,缓冲更多并将更大的块写入文件是有意义的)。

于 2009-03-15T22:17:15.203 回答
5
  1. 累积缓冲区中的位(单个字节可以称为“缓冲区”)
  2. 添加位时,将缓冲区左移并使用 OR 将新位放在最低位置
  3. 缓冲区已满后,将其附加到文件中
于 2009-03-15T22:18:53.280 回答
1

我做了类似的东西来模拟 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);                                                
        }           
    }
于 2013-08-13T20:08:10.570 回答
0

您将不得不使用位移位或二进制算术,因为您一次只能写入一个字节,而不是单个位。

于 2009-03-15T22:16:16.640 回答