Ssurge
Ssurge

Reputation: 29

Read bytes from a binary file, turn a few of them into ints in C

Let's say I have a binary file containing this:

0b 10 00 00 06 00 00 1a 66 32 2e 74 78 74 70 6f 72 .... I used hexdump -C file to get these values.

How can I read the first eight bytes and put them into an array and turn them into ints? In the end I want to have an int mybytes[8] which contains:

mybytes[0] = 11 
mybytes[1] = 16
.....
mybytes[4] = 6
.....
mybytes[7] = 26.

I tried reading those eight bytes using:

unsigned char mybytes[8];
fread(mybytes, 8, 1, myfile); 

And I can even print out the values I need like this:

for (k=0; k<4; k++)
printf("%d\n", mybytes[k]);

but I need to actually use those values. I don't understand how chars really work so I am a little confused here. I was thinking about writing all of them in a temporary text file and reading them later as ints... but I am sure there must be better methods out there.

Also, but not necessary. Is it possible to read four bytes at a time and find their decimal value? For example reading 0b 10 00 00 as a whole and having the value of 4107? I know how to calculate them if I have those four values separately in an array (whether in hex or decimal and yes I am aware of the fact that the whole number in hex would be 0000100b), but I am wondering if there is a faster way to do it.

Upvotes: 1

Views: 313

Answers (1)

Vality
Vality

Reputation: 6607

Assuming the file is in native endianness it should not be necessary to use a byte array at all, just do this:

int foo;
fread(&foo, sizeof(int), 1, myfile);
printf("%d", foo);

it will write directly into the int. By virtue of fread's ability to read multiple objects at once it is also possible to fill a whole array of ints at once with the following code (this usage of fread courtesy of @lurker):

int N = 4; // Change this to the number of ints in the file
int foo[N];
fread(data, sizeof(int), N, myfile);
for(int iter = 0; iter < N iter++)
{
    printf("%d", foo[iter]);
}

Upvotes: 1

Related Questions