简体   繁体   中英

Binary File Parsing; What's the difference between these two calls?

// assume file points to a file

struct myStruct
{
     WORD word;
     WORD word2;
};

Two competing codes: (1)

myStruct a;
a.word = 0xABCD;
a.word2 = 0xFADB;
fwrite(&a, sizeof(myStruct), 1, file);

output:
cdab dbfa

versus: (2)

DWORD word = 0xABCDFADB;
fwrite(&word, sizeof(DWORD), 1, file);

output:
dbfa cdab

My question is this: why isn't fwrite amenable to writing the structure? I would assume that (1) would have equivalent output to (2). However, the fwrite is reading each struct member variable individually (and then writing them in little-endian order). Instead, I was expecting (1) to read the whole struct as one contiguous chunk, and start writing binary data starting at the end of this chunk (instead of at the end of the first member variable).

Thoughts?

If you're on a little-endian architecture, whole structs aren't stored backwards; only the integers, pointers, and other numeric values are.

Thus, when you have a struct containing two WORD s, each WORD is stored in little-endian order, but the fields themselves aren't switched in memory. When you have a single DWORD , that's a single unit, and it will be stored in little-endian.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM