Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats with the zeroes in my binary file?

Tags:

c

linux

fwrite

So. I have been experimenting with fwrite().

On my system sizeof( int ) = 4. I have an array of ints that contains: 1, 2, 3, 4, 5 and 6.

When i write it to a binaryfile and view it with hexdump I get:

0000000 0001 0000 0002 0000 0003 0000 0004 0000
0000010 0005 0000 0006 0000                    
0000018

Whats does it write zeroes between the 4byte values?

like image 938
John Avatar asked Jan 15 '23 07:01

John


2 Answers

Because 1 (for example) represented as 4-byte hex is 00000001. Apparently you're on a little-endian system, hence the apparently back-to-front ordering when you inspect your file.

like image 94
Oliver Charlesworth Avatar answered Jan 16 '23 20:01

Oliver Charlesworth


Your hexdump is grouping two bytes as a single word and changing the endianness. On most systems, using hexdump -C changes the dump into canonical view which prevents the grouping. In hexadecimal, one character represents one nybble, and there are two nybbles per byte. So your 4-byte int should have 8 nybbles in total. Since your numbers are very small, most of your nybbles are 0.

like image 36
dreamlax Avatar answered Jan 16 '23 20:01

dreamlax