Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading