I have a binary file that contains 16-bit integer data and i want to convert it to ASCII readable data.
My question is how do I use fread(&buffer,sizeof(buffer)
or 16,1,fp);
to read the file and use again fwrite(buffer, sizeof(buffer)/7, 1, file);
to write the data to a file.
16 in fread
is 16-bit and wants to know where it goes or in what form it goes and if in fwrite I will put 7
for 7-bit.
Please provide a code snippet example in C. I want to have the resultant file to be an ordinary readable text file.
You have many things that are confusing.
Assuming buffer
is a magically sized properly to fit the file uint8_t
array, you can read it in (from a file fopen()
ed in binary mode ) using:
fread(buffer, sizeof buffer, in);
That'd give you all of the bits in buffer
, if it doesn't fail.
Then, the output is simply:
FILE * const out = fopen("numbers.txt", "wt");
if(out != NULL)
{
for(size_t i = 0; i < sizeof buffer; i += 2)
{
const unsigned int here = buffer[i] + 256 * buffer[i + 1];
fprintf(out, "%u\n", here);
}
fclose(out);
}
This assumes little-endian byte ordering in the binary file. Swap the indexes in the here
assignment for big-endian. It also assumes unsigned 16-bit numbers.
after adjusing my code as below the result i get unsigned int,since am expecting data result with alphabetical characters.what additional code can i add to turn it alphabetical?
#include<stdio.h>
int main()
{
FILE *fp,*out;
char buffer[256];
size_t i = 0;
fp=fopen("c:/Gosam/input.txt", "rb");
if(out != NULL)
{
fread(buffer, sizeof buffer,1, fp);
}
out = fopen("c:/Gosam/res.txt", "w");
if(out != NULL)
{
// buffer = (char*) malloc (sizeof(char)*Size);
for( i = 0; i < sizeof(buffer); i += 2)
{
const unsigned int var = buffer[i] + 256 * buffer[i + 1];
fprintf(out, "%u\n", var);
}
fclose(out);
}
fclose(fp);
}
these are my results but i want to turn them to alphabetical strings.
263
4294966987
4294967222
4294967032
64
4294967013
73
4294967004
90
4294967028
83
4294966975
37
4294966961
5
4294966976
82
4294966942
4294967022
4294966994
11
4294967024
29
4294966985
4294966986
4294966954
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.