0

I try to write a struct into file, then i found the endian of that is differet with the endian in the memory.

some test code:

void show_hex(unsigned char *p, int n)
{

    for (int i=0; i<n;i++){
        printf("%02X ",p[i]);
    }

}

int main()
{
    FILE *fp = fopen("as","w");
    struct X{
        int x,y;
    };
    struct X *p = malloc( sizeof(struct X));
    p->x = 0xFFEECCAA;
    p->y = 0xFFAADD;
    show_hex((unsigned char *) p, sizeof(struct X));
    fwrite(p, sizeof(struct X), 1, fp);
    fclose(fp);

    int f = open("as2",O_WRONLY);
    write(f, p, sizeof(struct X));
    close(f);
    return 0;
}

the problem out put : AA CC EE FF DD AA FF 00 //i know that is the little endian

tyw@um08:~/pro|master⚡ ⇒  hexdump as
0000000 ccaa ffee aadd 00ff                    
0000008
tyw@um08:~/pro|master⚡ ⇒  hexdump as2
0000000 ccaa ffee aadd 00ff                    
0000008

So the endin is different.

1
  • You could have tested this by using echo 1234 | hexdump instead of assuming the endian was wrong. When all else fails, man hexdump. Commented Mar 14, 2013 at 23:12

1 Answer 1

6

The endianness of the file isn't different than the memory. The default behavior of hexdump is to print the values as 16-bit shorts. What you are seeing is a different interpretation of the memory. Try hexdump -C

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.