如何在C中将单个位写入文件 [英] How to write single bits to a file in C
问题描述
提前感谢
您不能将单个位写入文件,分辨率为单个字节。
如果要写入位顺序,你必须批量,直到你有一个完整的字节,然后写。 Psuedo代码(虽然C样)将符合以下条件:
currbyte = 0
/ pre>
bitcount = 0
def writeBit(bit):
currbyte = currbyte<<< 1 | bit
bitcount ++
如果bitcount == BITS_PER_BYTE:
将currbyte写入文件
currbyte = 0
bitcount = 0
你想要更改个别位,你必须读取一个字节,使用bitwise操作操作它,然后写回。
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!
解决方案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.
这篇关于如何在C中将单个位写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!