How to write bits to a file?

六眼飞鱼酱① 提交于 2019-12-10 15:44:15

问题


How to write bits (not bytes) to a file with c#, .net? I'm preety stuck with it.
Edit: i'm looking for a different way that just writing every 8 bits as a byte


回答1:


The smallest amount of data you can write at one time is a byte.

If you need to write individual bit-values. (Like for instance a binary format that requires a 1 bit flag, a 3 bit integer and a 4 bit integer); you would need to buffer the individual values in memory and write to the file when you have a whole byte to write. (For performance, it makes sense to buffer more and write larger chunks to the file).




回答2:


  1. Accumulate the bits in a buffer (a single byte can qualify as a "buffer")
  2. When adding a bit, left-shift the buffer and put the new bit in the lowest position using OR
  3. Once the buffer is full, append it to the file



回答3:


You will have to use bitshifts or binary arithmetic, as you can only write one byte at a time, not individual bits.




回答4:


I've made something like this to emulate a 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);                                                
        }           
    }


来源:https://stackoverflow.com/questions/648651/how-to-write-bits-to-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!