How to write single bits to a file in C

假如想象 提交于 2019-11-29 16:18:41
paxdiablo

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.

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