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?
arris 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 madearran “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
arrso that it is of typechar, you can read your string in, and yourforloop 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.