Home > other >  The confuse of binary orders of writing struct into binary file with fwrite in C
The confuse of binary orders of writing struct into binary file with fwrite in C

Time:08-10

I am trying to use fwrite to write struct into binary file, but the bytes order of the binary file really confuses me. The struct is as follow:

(gdb) p data[0]@10
$1 = {{alphCount = 58, ascii = 97 'a'}, {alphCount = 1, ascii = 10 '\n'}, {alphCount = 31, ascii = 98 'b'}, {alphCount = 1,
    ascii = 10 '\n'}, {alphCount = 20, ascii = 99 'c'}, {alphCount = 1, ascii = 10 '\n'}, {alphCount = 31, ascii = 100 'd'}, {
    alphCount = 1, ascii = 10 '\n'}, {alphCount = 377, ascii = 101 'e'}, {alphCount = 1, ascii = 10 '\n'}}

And the result of hexdumping the binary file is as follow:

0000000 003a 0000 0161 0000 0a00 001f 0000 0162
0000010 0000 0a00 0014 0000 0163 0000 0a00 001f
0000020 0000 0164 0000 0a00 0179 0000 0165 0000
0000030 0a00                                   
0000032

In addition, I have used "__attribute__((packed))" to disable the alignment of struct, so the size of my struct would be 5 bytes.

And the fwrite code is as follow:

fwrite(data, 5, 10, stdout);

Why the first byte of the file is "00" rather than "3a"? In my knowledge, I am using the intel architecture, and the order of storing bytes would be little-endian, I thought the first few bytes of the file would be like "3a00 0000 61", but it actually isn't like what I thought.

Any advise would be appreciated, thanks in advance!

CodePudding user response:

You are mixing representations:

Why the first byte of the file is "00" rather than "3a"? In my knowledge, I am using the intel architecture, and the order of storing bytes would be little-endian, I thought the first few bytes of the file would be like "3a00 0000 61", but it actually isn't like what I thought.

Well, yes. But you do not look at plain byte values. You are looking at 16bit words. For this the byte order has already be taken into account and the first 2 bytes 3a 00 are shown as 003a.

If you switch your hex dump tool to 32bit values you would probably get 0000003a xxxxxx61 and when you switch to single bytes you will get 3a 00 00 00 61

CodePudding user response:

Why the first byte of the file is "00" rather than "3a"?

It's not.

In my knowledge, I am using the intel architecture, and the order of storing bytes would be little-endian

Exactly, so 003a is stored as 3a 00

The first byte is 3a, and the second 00.

Perhaps you should be using hexdump -C instead of just hexdump.

  • Related