Hexdump vs Actual File Contents

hexdumplinuxPHP

When I do hexdump filename.txt I get the following as output:

00000000 ac5a 5afb c08d 5d15 26d0 2491 e8c9 8917
00000010 

When I do <?= bin2hex(file_get_contents('filename.txt')); ?> I get this:

5aacfb5a8dc0155dd0269124c9e81789

So why is hexdump suggesting the contents should be ac5a5afbc08d5d1526d02491e8c98917 when PHP is suggesting they ought to be 5aacfb5a8dc0155dd0269124c9e81789? Am I just not interpreting the output of hexdump correctly?

Best Answer

The difference is big-endian vs. little-endian order.

Start with the first four bytes of hexdump output: ac5a 5afb. Now switch the byte order to get:

5aac fb5a

Compare this with the PHP output:

5aac fb5a

They match.

By default, BSD hexdump displays output based on the machine's endianness. If you don't want that, you can specify the -C option to get output byte-by-byte rather word-by-word:

$ hexdump filename.txt 
0000000 ac5a 5afb c08d 5d15 26d0 2491 e8c9 8917
0000010
$ hexdump -C filename.txt 
00000000  5a ac fb 5a 8d c0 15 5d  d0 26 91 24 c9 e8 17 89  |Z..Z...].&.$....|
00000010
Related Question