简体   繁体   English

将原始二进制文件写入C中的文件

[英]write raw binary to file in C

I am trying to write raw binary bits at a time to a file. 我正在尝试一次将原始二进制位写入文件。

I have found an example that uses unsigned char -> https://stackoverflow.com/a/2666669/1541965 我发现了一个使用无符号字符的示例-> https://stackoverflow.com/a/2666669/1541965

But the minimum size is 8 bit (because of the unsigned char 0 to 255). 但是最小大小为8位(因为无符号字符0至255)。

Is there a way to write bits to a file in a more direct way? 有没有一种方法可以以更直接的方式将位写入文件?

Thanks. 谢谢。

You haven't said what operating system you're using. 您尚未说出正在使用什么操作系统。 But generally the smallest unit you get to write to a file is one 8-bit byte. 但通常,您写入文件的最小单位是一个8位字节。 If you want to write individual bits, you'll need to assemble them into bytes in your own code. 如果要写入单个位,则需要在自己的代码中将它们组合成字节。 I don't know of any OS whose file IO facilities allow writing of individual bits. 我不知道任何操作系统的文件IO设施允许写入单个位。

No, there isn't, at least not directly. 不,至少没有。 C's I/O model for binary files is that they're sequences of bytes (typically 8 bits). C的二进制文件的I / O模型是它们是字节序列(通常为8位)。

What you can do is, in your own code, write a function that takes a 1-bit value and gathers the bits into a byte, writing them to the file when it's received 8 bits. 您可以做的是,用自己的代码编写一个函数,该函数接受一个1位的值并将这些位收集到一个字节中,并在收到8位时将其写入文件。 You'll also need to do an additional write at the end if the byte value hasn't been filed yet. 如果尚未提交字节值,则还需要在末尾进行其他写操作。

It's not possible to write a partial byte; 不可能写部分字节。 you can, if necessary, pad the last byte with zeros if necessary. 您可以根据需要将最后一个字节填充为零。

(The C standard requires a byte to be at least 8 bits, but it permits it to be more. The number of bits in a byte is specified by CHAR_BIT , defined in <limits.h> . CHAR_BIT is going to be exactly 8 on any system you're likely to encounter.) (C标准需要一个字节是至少 8位,但它允许它要多。由指定位的一个字节的数CHAR_BIT ,在定义<limits.h>CHAR_BIT将是准确上8您可能会遇到的任何系统。)

Computer architecture does not allow you to split the byte, which is 8 bits. 计算机体系结构不允许您拆分8位字节。 PCs work on 8 bits. PC工作在8位上。 Turing's Colossus worked on 5 bits (because in Baudot's code the number 2^5 is enough ). 图灵的巨像工作在5位上(因为在Baudot的代码中2 ^ 5就足够了)。

The microprocessors do not have instructions to deal with units less than a byte (even bits operations like or, use on 1,2,4,8 bits). 微处理器没有指令来处理小于一个字节的单元(偶数位操作如,或在1,2,4,8位上使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM