C读取二进制数并将其转换为Ascii代码 [英] C fread binary number and convert it to Ascii code
问题描述
我正在尝试从文件中读取以下二进制文件(01100001),并将其转换为ASCII代码(97),但是使用fread时,我得到了一个很大的数字. 文件"c:/input.txt"仅包含以下行-01100001 数组值的printf打印大数字,例如825241648
I'm trying to read the following binary (01100001) from a file and convert it to ascii code (97), but when using fread i'm getting a very big numbers. the file "c:/input.txt" contain only the following line -01100001 printf of the array values print big numbers, such as 825241648
我的代码:
int main()
{
unsigned int arr[8];
int cnt,i,temp=0;
FILE * input;
if(!(input=fopen("C:/input.txt","r")))
{
fprintf(stderr,"cannot open file\n");
exit(0);
}
cnt = fread(arr,1,8,input);
for(i=0;i<cnt;i++)
{
printf("%d\n",arr[i]);
}
return 0;
}
知道为什么吗?
推荐答案
arr
是一个整数数组.但是您只读了8个字节.因此,第一个整数将具有较大的值,而第二个整数将具有较大的值,但此后它们将具有垃圾值. (您将arr
设置为自动"变量,该变量分配在堆栈上,因此其中将具有随机垃圾;如果将其设置为静态变量,则它将被预先初始化为零字节.)
arr
is an array of integers. But you read only 8 bytes into it. So your first integer will have some large value, and so will your second, but after that they will have garbage values. (You made arr
an "automatic" variable, which is allocated on the stack, so it will have random garbage in it; if you made it a static variable it would be pre-initialized to zero bytes.)
如果将arr
的声明更改为char
类型,则可以读取字符串,并且for
循环将一次循环遍历这些字节.
If you change the declaration of arr
so that it is of type char
, you can read your string in, and your for
loop will loop over those bytes one at a time.
然后,您可以编写一个字符串到二进制的转换器,或者您可以使用strtol()
将基数设置为2进行转换. GCC很好,但是Microsoft C没有.
Then you can write a string-to-binary translator, or alternatively you could use strtol()
to do the conversion with the base set to 2. strtol()
is not available in all compilers; GCC is fine but Microsoft C doesn't have it.
这篇关于C读取二进制数并将其转换为Ascii代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!