Reputation: 59
I try to read value from binary file. I know offset (3201) and use it.
Example code:
FILE *bin_file;
int *job_id_buffer;
bin_file = fopen("sample.sgy", "rb");
if (bin_file == NULL)
{
// ... skipped ...
}
fseek(bin_file, 3201, SEEK_SET);
job_id_buffer = (int*)malloc(sizeof(int));
fread(job_id_buffer, sizeof(int), 1, bin_file);
printf("%d\n", (int)job_id_buffer[0]);
fclose(bin_file);
Looks like I don't know how to read value correctly.
But problem is that when I get result, the value is 993024, while I 100% know that correct value is 9999.
Could you, please, help me to understand what I do incorrectly?
Thank you in advance!
Upvotes: 0
Views: 80
Reputation: 12630
A quick look at the values you got:
Expected: 9999 = 0x0000270F
Received: 993024 = 0x000F2700
From this we can see two things:
0F27
is 270F
with swapped bytes. Apparently, the byte order (endiannes) inside the file is not the same as that in memory;
If only the byte order was swapped, you would be getting 0x0F270000
from the file, but the value seems to be shifted by one byte.
This can mean one of two things, depending on the endianness of the file:
If the file is little-endian (and the CPU is big-endian), you should be seeking to offset 3202
instead of 3201
.
If the file is big-endian (and the CPU is little-endian), you should be seeking to offset 3200
instead of 3201
.
So, check the endianness of the file and correct your offset; then, convert the data read from the endianness of the file to the endianness of your CPU (reverse the bytes in this case) to get the correct value.
To create code that is correct on any CPU, you may be able to use be32toh()
, or le32toh()
, to convert big-endian, or little-endian respectively, file data to the right CPU endianness.
Upvotes: 5