C如何从文件中读取一个位

the*_*123 3 c binary bit-manipulation fgets

我正在读取C中的二进制文件:infile=fopen(input, "rb")我试图一次读取每个位,所以如果文件内容是:

"你好"

'h'的ascii值是104二进制的1101000.

是否有一个fgetbit()方法可以调用并分配给基本类型?EX:

int my_bit=fgetbit(infile); //value of my_bit would be 1 for hello example.
Run Code Online (Sandbox Code Playgroud)

Gov*_*mar 8

在文件I/O期间,您不能获得比字节更精细的粒度,但如果您真的想在位级工作,则可以使用位掩码或位移来在读取字节后隔离所需的位出文件.

例如,输出/检查字节中的每个位:

#include <limits.h> // for CHAR_BIT

...

unsigned char b = 0xA5; // replace with whatever you've read out of your file
for(i = 0; i < CHAR_BIT; i++)
{
    printf("%d", (b>>i)&1); 
}
Run Code Online (Sandbox Code Playgroud)

要隔离字节中最重要的位:

unsigned char mask = 0x80; // this value may differ depending on your system's CHAR_BIT
unsigned char value = /* read from file */;
if(value&mask)
{
   // MSB is set
}
else
{ 
   // MSB is clear
}
Run Code Online (Sandbox Code Playgroud)

  • 好了,现在介绍对示例很有意义。 (2认同)