如何单个位写在C文件 [英] How to write single bits to a file in C

查看:161
本文介绍了如何单个位写在C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编程的熵编码算法,我想要写单个位像一间codeD字符的文件。比如我想写011文件,但如果你将其存储为字符它会占用3个字节,而不是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?

在此先感谢!

推荐答案

您不能单个位写入一个文件,分辨率为一个字节。

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

如果你想写顺序位,你有一批起来,直到你有一个完整的字节,然后写。 Psuedo- code(虽然C-等)的,将是大致相同的:

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

您要的变更的各个位,你有一个字节读取,使用<一个href=\"http://stackoverflow.com/questions/1746613/bitwise-operation-and-usage/1746642#1746642\">bitwise操作来操纵它,然后写回。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆