用C语言从文本文件中读取8位二进制数
我试图从一个C语言的文本文件中读取数据,该文件包含一个8位二进制数列表,用于另一个函数用C语言从文本文件中读取8位二进制数,c,file,parsing,text,C,File,Parsing,Text,我试图从一个C语言的文本文件中读取数据,该文件包含一个8位二进制数列表,用于另一个函数 The text file is formatted like: 01101101 10110110 10101101 01001111 11010010 00010111 00101011 等等 这就是我想做的 伪码 void bincalc(char 8_bit_num){ //does stuff } int main() { FILE* f = fopen("test.txt", "r
The text file is formatted like:
01101101
10110110
10101101
01001111
11010010
00010111
00101011
等等
这就是我想做的
伪码
void bincalc(char 8_bit_num){
//does stuff
}
int main()
{
FILE* f = fopen("test.txt", "r");
int n = 0, i = 0;
while( fscanf(f, "%d ", &n) > 0 ) // parse %d followed by a new line or space
{
bincalc(n);
}
fclose(f);
}
我想我走的是对的,不过我非常感谢你的帮助 这不是标准曲目,但还可以。您正在扫描读取
int
s的文件,因此它将读取字符串并将其解释为十进制数,然后您应将其转换为相应的二进制,即将1010十进制转换为2^3+2^1=9十进制。这当然是可能的,您只需要将十的幂变换为二的幂(1.10^3+0.10^2+1.10^1+0.10^0到1.2^3+0.2^2+1.2^1+0.2^0)。请注意,这适用于8位数字,但不能用于太大的数字(16位不会)
更常见的方法是直接读取字符串并解码字符串,或者逐字符读取并进行增量转换。如果您希望在末尾有一个数字,我建议如下所示:
int i;
char buf[10], val;
FILE* f = fopen("test.txt", "r");
while( ! feof(f) ) {
val = 0;
fscanf(f, "%s", buf);
for( i=0; i<8; i++ )
val = (val << 1) | (buf[i]-48);
/* val is a 8 bit number now representing the binary digits */
bincalc(val);
}
fclose(f);
inti;
char-buf[10],val;
文件*f=fopen(“test.txt”、“r”);
而(!feof(f)){
val=0;
fscanf(f,“%s”,buf);
对于(i=0;i我认为这是一个可能的解决方案,我将其简化,以便您能够理解并适应您的需要。您只需在每行重复此操作
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file =fopen("data","r");
char *result=calloc(1,sizeof(char));
char line[8];
int i=0;
for(;i<8;i++)
{
char get = (char)getc(file);
if(get == '0')
*result <<= 1;
else if(get == '1')
*result = ((*result<<1)|0x1) ;
}
printf("->%c\n",*result);
return 0;
}
#包括
#包括
内部主(空)
{
FILE*FILE=fopen(“数据”,“r”);
char*result=calloc(1,sizeof(char));
字符行[8];
int i=0;
对于(;i我不知道如何为fscanf()
指定二进制格式,但是您可以像这样转换二进制字符串
#include <stdio.h>
#include <stdlib.h>
void fatal(char *msg) {
printf("%s\n", msg);
exit (1);
}
unsigned binstr2int(char *str) {
int i = 0;
while (*str != '\0' && *str != '\n') { // string term or newline?
if (*str != '0' && *str != '1') // binary digit?
fatal ("Not a binary digit\n");
i = i * 2 + (*str++ & 1);
}
return i;
}
int main(void) {
unsigned x;
char inp[100];
FILE *fp;
if ((fp = fopen("test.txt", "r")) == NULL)
fatal("Unable to open file");
while (fgets(inp, 99, fp) != NULL) {
x = binstr2int(inp);
printf ("%X\n", x);
}
fclose (fp);
return 0;
}
程序输出
6D
B6
AD
4F
D2
17
2B
逐行读取文件,然后与base2
一起使用
或者,如果保证文件不长,您也可以读取(动态分配)内存中的全部内容,并使用endptr
参数。只需读取整行(fgets
或fscanf(f,“%s…”)
),然后逐个解析。您的建议不起作用。以这种方式读取的十进制数远远大于存储在字符中的十进制数,您最多只能存储三个“but”。将十进制数解析为二进制是可能的,但将实际字符解析为字符串可能更容易。代码读取的是int(4字节)bincalc函数需要一个字符(1字节),建议通过读取8个字符并将其压缩为一个8位字符,然后调用bincalc函数,将输入转换为字符compression@user3629249:…当然,在这个函数中没有什么可以做的了…feof()在尝试读取文件结尾之前无效。通常,永远不要使用feof控制循环。此答案的其余部分看起来不错
6D
B6
AD
4F
D2
17
2B