0

I have created the binary image filled with incremental numbers by using below c program.

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
        FILE *w_file;
        long cnt = 0, buf_cnt = 0,pn_cnt = 0x0;
        char buffer[4194305];


        w_file = fopen ( "test.img" , "wb" );
        if (w_file==NULL)
        {
                perror("File error");
                return -1;
        }
        for (cnt = 0; cnt < (4096*1024); cnt++)
        {
                buffer[cnt] = cnt;
        }

        fwrite(buffer, 4096, 1024, w_file);

        fclose (w_file);
        return 0;

}  

But when I've checked the image with hexdump, i noticed that all the bytes are swapped. Why this happens?

sample screenshot of hexdump:

0000000 0100 0302 0504 0706 0908 0b0a 0d0c 0f0e
0000010 1110 1312 1514 1716 1918 1b1a 1d1c 1f1e
0000020 2120 2322 2524 2726 2928 2b2a 2d2c 2f2e
0000030 3130 3332 3534 3736 3938 3b3a 3d3c 3f3e
0000040 4140 4342 4544 4746 4948 4b4a 4d4c 4f4e
0000050 5150 5352 5554 5756 5958 5b5a 5d5c 5f5e
0000060 6160 6362 6564 6766 6968 6b6a 6d6c 6f6e
0000070 7170 7372 7574 7776 7978 7b7a 7d7c 7f7e
0000080 8180 8382 8584 8786 8988 8b8a 8d8c 8f8e
0000090 9190 9392 9594 9796 9998 9b9a 9d9c 9f9e
00000a0 a1a0 a3a2 a5a4 a7a6 a9a8 abaa adac afae
00000b0 b1b0 b3b2 b5b4 b7b6 b9b8 bbba bdbc bfbe
00000c0 c1c0 c3c2 c5c4 c7c6 c9c8 cbca cdcc cfce 
Akaash
  • 61
  • 1
  • 8
  • Are you sure? Because when I run this code and run `xxd -l 16 test.img` it outputs `00000000: 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f ................` – Cornstalks Jun 01 '17 at 13:16
  • By the way, valid return values from main are generally 0 (success) and 1 to 127 (failure). Outside of that, like -1, is not good practice. – John Zwinck Jun 01 '17 at 13:17
  • Unrelated: `char buffer[4194305];` is ugly. Why don't you write `char buffer[4096*1024];`? – Jabberwocky Jun 01 '17 at 13:17

1 Answers1

2

Hexdump swaps the bytes when displaying.

hexdump confusion

If you use hexdump -C ..., you're likely to get the expected result.

Sam Pagenkopf
  • 258
  • 1
  • 5