17

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?

1

1 Answer 1

25

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
2
  • 4
    To add a bit: hexdump is showing the data interpreted as sixteen-bit words. bin2hex is showing one byte at a time, as would be appropriate for ASCII characters or similar. On x86 and x64 (and other little-endian CPUs), the first byte of a multi-byte integer contains the least significant bits. So if the first thing in your file was a 16-bit integer containing the value 1, displaying it as bytes would show 01 00 , but displaying it as a 16-bit word would show 0001 (natural reading order, LSB on the right, as we do in everyday use of decimal numbers). en.wikipedia.org/wiki/Endianness Oct 17, 2014 at 0:55
  • To add on @JamieHanrahan's comment, read: "and all other little-endian CPUs", as this is the very point of the endianness.
    – glglgl
    Oct 17, 2014 at 9:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .