1

I wanted to get 16 bytes from a binary file, starting from 5th byte, no separation of bytes or words by spaces.

hexdump will do what I want, just the offset column is disturbing the output:

$ hexdump -s5 -n16 -xe '/1 "%01X"' binfile

od does the task fine as well and can even be told to suppress the offset column, although I had to use sed to get rid of the spacing:

$ od -An -tx1 -j5 -N16 | sed 's/ //g' binfile

I am sure it will work without sed, but as I had many issues with od in hex mode related to endianness (swapped bytes), this is not as easy as it looks. For instance, changing -tx1 to anything higher will swap the bytes and mess up the 128-bit value that I want. -tx1 is fine, but unlike hexdump I haven't found a way to get rid of the spaces while keeping byte order as-is at the same time.

4

The -x option instructs hexdump to display offsets, and specifying a format afterwards doesn't suppress that. Get rid of the -x option.

$ hexdump -s5 -n16 -e '/1 "%01X"' <<<@abcdefghijklmnopqrstuvwxyz; echo
65666768696A6B6C6D6E6F7071727374

If you want to read two-byte values in the platform's endianness the way -x does (which swaps the two bytes on little-endian platforms such as x86 and ARM¹), use %02X instead of %01X.

¹ ARM CPUs support both endiannesses, but almost all Unix systems use them in little-endian mode.

  • Thanks! Though it almost feels embarrassing now, there is a good reason why I didn't get that first time. First of all, I come from od times (when the hexdump|hd tool didn't even exist) - and the -x option meant hex mode (since od's default mode is octal). Second, the man page of hexdump reads "Two-byte hexadecimal mode" for its -x option. The offset thing is just hidden away in the following text, but I thought, hey, 2B hex mode, that's just what I'm in need of here. :) – syntaxerror Nov 21 '15 at 0:34
  • Well, this gets even more interesting. Though you said that the -x option triggers the offset column, hexdump appears to use it per default in some cases. That is, if the only argument to hexdumpis the filename, offset column will be displayed too! Yes, without specifying -x. (Just figured that out.) – syntaxerror Nov 21 '15 at 0:43
  • @Gilles: How %02X swap endianness? – cuonglm Nov 21 '15 at 1:50
  • 1
    @cuonglm %02X prints two-byte values at a time. Each value is read in the platform's endianness and is printed with the most significant hexadecimal digit first. The most common platforms running Unix today (x86 as well as any ARM that you're likely to encounter) are little-endian, so in this two-byte value the first byte contains the least significant two hexadecimal digits. I should have mentioned that this depends on the platform's endianness. – Gilles Nov 21 '15 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.