Tag Archives: c

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.