问题
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
My code:
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;
}
any idea why?
回答1:
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.)
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.
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.
回答2:
Pl. see if the code (Compiled using gcc on Linux) below works for this.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr[8];
int cnt,i,temp=0;
FILE * input;
if((input=fopen("data","r"))==NULL)
{
fprintf(stderr,"cannot open file\n");
exit(1);
}
//Read the 8 bytes in a character array of size 8
cnt = fread(arr,1,8,input);
for (i = 0; i < cnt; i++)
{
//Now change it to 0/1 form by substracting 48
arr[i] = arr[i] - '0';/* Ascii of 0 = 48*/
//Also Left shift..
arr[i] = arr[i] << (cnt - (i+1));
//Now Bit wise OR with the integer...
temp = temp | arr[i];
}
printf("The ascii value is %d and the character is %c\n", temp, temp);
return 0;
}
回答3:
You first declare unsigned int arr[8];
which means 8 integers or more precisely 8*4=32 bytes. After that you read 8 bytes and then again try to output 8 integers. I suppose you want to read 8 bytes and output them as numbers? If you change type int
to char
, code might work. If file size is 32 bytes and contains integers, you may want to change fread() like this: fread(arr,sizeof(int),8,input);
来源:https://stackoverflow.com/questions/11326852/c-fread-binary-number-and-convert-it-to-ascii-code