写位在C文件 [英] Writing bits to a file in C

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

问题描述

我有这样的字符串:101
我想将其写入文件,在C,而不是文字:101等8位×字符。但直接使用字符串作为位:位1,比特0和比特1,这样该文件将成为3位

I have this string: "101" I want to write it to a file, in C, not as text: "101" and so 8 bits x char. but directly use the string as bits: the bit "1", the bit "0" and the bit "1", so that the file will be of 3 bits.

难道不可能性?
我搜索在网络上,我试着这样做:

Is it possibile? I searched on the web and I tried doing this:

char c[25] = "101";
FILE *binFile = fopen("binFile.bin", "wb");
int x = atoi(c);
fwrite(&x, sizeof(x), 1, binFile);

但在最后,当我确认文件的字节时,Windows说我,这是4字节的文件!而不是3比特!

But at the end, when I verify files's bytes, Windows says me that it is 4bytes file! And not 3bits!

我怎么能做到这一点,如果可能的话?非常感谢。

How can I do this, if it is possible? Thanks a lot.

推荐答案

所有filesystems¹处理文件中的字节术语(和一个更大的粒度分配存储空间,在一个时间最小512字节)。有没有办法,你会得到一个文件,是的 3位的长。

All filesystems¹ deal with files in terms of bytes (and allocate storage space with a much larger granularity, 512 bytes at a time minimum). There's no way you are going to get a file that is 3 bits long.

你能做的最好的是使用了一整字节,但忽略其位5。要做到这一点(假设数总是要适应一个字节),输入字符串转换为整数类型:

The best you can do is use up one whole byte but ignore 5 of its bits. To do that (assuming that the number is always going to fit into a byte), convert the input string to an integral type:

long l = strtol(c, 0, 2);

然后得到其最显著字节:

Then get its least significant byte:

unsigned char b = l & 0xffl;

并将其写入文件:

And write it to the file:

fwrite(&b, 1, 1, binFile);


¹好吧,也许不是全部。可能有一些研究人员的地方,实验位大小的文件系统。我不知道。


¹ Well, maybe not all. There might be some researchers somewhere that experiment with bit-sized filesystems. I wouldn't know.

这篇关于写位在C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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