Search code examples
cfreadhexdump

Can't get the exact hexadecimal value from reading a file


Code =>

#include<stdio.h>

typedef struct {
    unsigned short c2;
    unsigned long c4;
} TAKECH;

int main() {
    TAKECH tch;
    FILE *fp_in;

    fp_in = fopen("in.txt","rb");

    fread(&tch,6,1,fp_in);

    printf("First two bytes: %x\n",tch.c2);
    printf("Next four bytes: %x\n",tch.c4);

    fclose(fp_in);

    return 0;
}

Output =>

First two bytes: 6261
Next four bytes: bfd56665

in.txt =>

abcdef

Hexeditor(vim editor :%!xxd) show this =>

0000000: 6162 6364 6566 0a                        abcdef.

Need explanation of output:

First two bytes: 6261 <-- Why is it in reverse order?

First two bytes: 6162 <-- Shouldn't this be?

Why can't I get 6364 in output? How can i get the next four bytes(6364 6566) with printf("Next four bytes: %x\n",tch.c4); Why do I get Next four bytes: bfd56665 , where does bfd5 come from?

Any answer will be highly appreciated.

Thanks in advance.


Solution

  • Changing a TAKECH struct as follow :

    typedef struct {
        unsigned short c2;
        unsigned long c4;
    } __attribute__((packed)) TAKECH;
    

    Here's an explanation about __attribute__((packed).

    The byte order is up to a little-endian cpu or a big-endian cpu. If you executed your code in a big-endian cpu, your opinion was right. But The PC is a little-endian cpu. Currently the most platform used a little-endian mode, although supported a big-endian mode. Here's more detail.