Thursday, June 30, 2011

3 different ways of dumping hex contents of a file

 At times, when you are doing any conversion of ascii to hex or to octal, we would like to view the hex contents or the hex dump of the file, be it ascii or binary. Let us see in this article the different ways to do it:

Let us contain a sample file, say file1, with the following content:
$ cat file1

1. Many unix flavors has a command called, hexdump. One of the functions of this hexdump command, as the name suggests, is to dump the hex contents of the file:
$ hexdump file1
0000000 6577 636c 6d6f 0a65
     The above output shows the hex contents of the ascii file content "welcome". And it is in big endian format. However, this output is not easier to interpret in case of a file with lot of contents since it becomes harder to match the ascii with hex. hexdump has an '-C" option which will map the ascii to hex and also displays in little endian format:
$ hexdump -C file1
00000000  77 65 6c 63 6f 6d 65 0a              |welcome.|
     If we see above, hex of 'w' is 77, 'e' is 65 and so on.

2. Another command, od , is quite frequently used in Unix world for octal dump of a file. However, the od command also has options(-x)  to do the hex dump of a file and the output is in big endian format:
$ od -x file1
0000000 6577 636c 6d6f 0a65
  To make this output more readable, use the "-c" option :
$ od -xc file1
0000000 6577 636c 6d6f 0a65
               w   e   l   c   o   m   e  \n
3. The last one is a very rarely used command, xxd. xxd command is a little special in the sense, apart from displaying the hex contents of a file, it can also do the reverse conversion as well(-r).
$ xxd file1
0000000: 7765 6c63 6f6d 650a                    welcome.
Let us take this hex content to a file, say file2:
$ cat file2
000000: 7765 6c63 6f6d 650a
Now, let us use the -r option to reverse the contents:
$ xxd -r file2
Happy Dumping!!!


  1. I am sure that you must have tested endianess of your machine. My understanding suggests that your output is always is in little endian, even with 2 byte display using hexdump. With -C flag you just print 1 byte at a time.