I'm trying to read a binary file that has a sequence of integers, a file that has 100 integers in sequence. The beginning of the sequence is:
20 2 22 4 22 10 5 5 4 1 ...
Using the xxd -b bin_100.bin
command
I got the following result:
binary
But I'm not able to store these numbers in integers, when I print the results they appear like this
335544320
33554432
369098752
67108864
For now my code is like this, I don't know what could be wrong (and I don't understand much about reading files in C)
int readBinary(char* file) {
FILE *binary;
int result;
int addresses[100];
size_t read_size;
char local[100];
snprintf(local, sizeof(local), "assets/%s", file);
binary = fopen(local, "rb");
if (binary == NULL)
return 0;
result = fread(&addresses[0], sizeof(int), 100, binary);
for(int i = 0; i < result; i++) {
printf("%d: %d\n", i, addresses[i]);
}
return 1;
}
x86 is little-endian. Your file is big-endian.
This looks like it might be homework, so I'll tell you what you need to know, but I won't do it for you.
htonl
will convert from your host's endianness to big-endianness. ntohl
will convert from big-endianness to your host's endianness. You need one of them.