3

I am programming an entropy coding algorithm and I want to write single bits like an encoded character to a file. For example I want to write 011 to a file but if you would store it as character it'd take up 3 Bytes instead of 3 Bits. So my final question is: How can I write single bits to a file?

Thanks in advance!

iPh1ps99
  • 97
  • 1
  • 7
  • You can't. You must write at least a byte. – Andrew Barber Dec 21 '14 at 12:48
  • To clarify, I think OP misstated that a character would take 3 bytes, but it only takes up one byte, hence the answers specifying a single byte needing to be used. – wxz Jul 22 '21 at 20:53

1 Answers1

7

You can't write individual bits to a file, the resolution is a single byte.

If you want to write bits in sequence, you have to batch them up until you have a full byte, then write that. Psuedo-code (though C-like) for that would be along the lines of:

currbyte = 0
bitcount = 0
def writeBit (bit):
    currbyte = currbyte << 1 | bit
    bitcount++
    if bitcount == BITS_PER_BYTE:
        write currbyte to file
        currbyte = 0
        bitcount = 0

Of you want to change individual bits, you have to read in a byte, use bitwise operations to manipulate it, then write it back.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • To be clear, this is a limitation of C and not an operating system issue? As in, the smallest data type in C is a char which is a single byte, so you can't modify only a single bit in C. From the operating system level, however, isn't it the case that even if your language allowed you to write a single bit, the OS would have to write back an entire page of memory back to disk because of the way paging works in modern OSes? – wxz Jul 22 '21 at 20:50