How to write single bits to a file in C

前端 未结 1 1739
悲哀的现实
悲哀的现实 2020-12-21 17:53

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

相关标签:
1条回答
  • 2020-12-21 18:28

    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.

    0 讨论(0)
提交回复
热议问题