Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - binary reading, fread is inverting the order

Tags:

c

binaryfiles

fread(cur, 2, 1, fin)

I am sure I will feel stupid when I get an answer to this, but what is happening?

cur is a pointer to a code_cur, a short (2 bytes), fin is a stream open for binary reading.

If my file is 00101000 01000000

what I get in the end is

code_cur = 01000000 00101000

Why is that? I am not putting any contest yet because the problem really boils down to this (at least for me) unexpected behaviour.

And, in case this is the norma, how can I obtain the desired effect?

P.S.

I should probably add that, in order to 'view' the bytes, I am printing their integer value.

printf("%d\n",code_cur)

I tried it a couple times and it seemed reliable.

like image 517
Temitope.A Avatar asked Sep 28 '22 21:09

Temitope.A


1 Answers

As others have pointed out you need to learn more on endianness.

You don't know it but your file is (luckily) in Network Byte Order (which is Big Endian). Your machine is little endian, so a correction is needed. Needed or not, this correction is always recommended as this will guarantee that your program runs everywhere.

Do somethig similar to this:

{
    uint16_t tmp;

    if (1 == fread(&tmp, 2, 1, fin)) { /* Check fread finished well */
        code_cur = ntohs(tmp);
    } else {
        /* Treat error however you see fit */
        perror("Error reading file");
        exit(EXIT_FAILURE); // requires #include <stdlib.h>
    }
}

ntohs() will convert your value from file order to your machine's order, whatever it is, big or little endian.

like image 108
Toni Homedes i Saun Avatar answered Nov 27 '22 10:11

Toni Homedes i Saun