Reading and writing bits to a file in c

When trying to implement a lzw compressor for a university class, I discovered that in c, the minimum amount of data you can write/read to a file is 1 byte, mostly because of the filesystems.

To workaround that, I wrote a simple bit buffer. It is capable of writing/reading bits of any length to/from a file. I licensed it over GPLv2 in case it is useful to anybody out there. Feel free to use/modify it:

To read bits from the file, you will want to call bb_read until it returns NULL. To write, don’t forget to call ff_flush after finishing so any remaining bits that didn’t complete a byte are written to the file.

One thought on “Reading and writing bits to a file in c”

  1. I did this code for a class a couple of years ago. I just used a different approach to the writting technique:

    I always wrote incoming bits on the rightmost side of the byte, this way, i could easily avoid that if/else statement on line 80, it should look like this:

    // Clears all bits of the incoming byte except for the first one
    bits[i] &= 1;
    // Move buffer bits 1 step to the left, leaving space for the incoming bit
    buffer->bits <bits |= bits[i];

    But either way, your code looks very good 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.