stack_underflow
stack_underflow

Reputation: 41

How to get specific format using hexdump or xxd?

I require the hexdumps of a number of files in a specific format:

00000000 4D 5A 90 00 03 00 00 00 04 00 00 00 FF FF 00 00

However, using hexdump or xxd I can only manage to get the above with a colon after the address and the ASCII text to the right of it, e.g.:

00000000: 4D 5A 90 00 03 00 00 00 04 00 00 00 FF FF 00 00 
MZ..............

I got the above using the command

xxd -g 1 -u filename

Any ideas?

Upvotes: 3

Views: 14838

Answers (2)

Murphy
Murphy

Reputation: 3999

hexdump is able to produce this output, and provides much more options, once you figure out the somewhat arcane, yet powerful, format syntax.

$ hexdump -v -e '"%08_ax" 16/1 " %02X" "\n"' en.gif 
00000000 47 49 46 38 37 61 10 00 0A 00 A1 03 00 CC 00 00
00000010 44 44 CC FF FF FF FF BB 66 2C 00 00 00 00 10 00
00000020 0A 00 00 02 25 8C 20 61 A8 97 BA 92 8B 10 BA CB
00000030 AA 45 FC 59 01 82 C0 18 96 E3 89 A6 64 79 AC 6C
00000040 E5 74 DA 26 D6 F3 84 67 41 01 00 3B

The format in detail:

  • "%08_ax" is the offset in hexadecimal, 8 digits with leading zeroes.
  • 16/1 " %02X" displays 16 bytes per iteration (line), one byte per block, each block formatted as 2 uppercase hexadecimal digits with leading zeroes and preceeding space.
  • "\n" finishes each iteration (line) with a newline.

Upvotes: 4

Shawn
Shawn

Reputation: 52439

od is one way:

After creating an example file via

perl -e 'print map { chr hex } @ARGV' 4D 5A 90 00 03 00 00 00 04 00 00 00 FF FF 00 00 > foo.bin

getting a hex dump of it:

$ od -Ax -t x1 foo.bin
0000000 4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00
0000010

The key here is the -t FORMAT argument. In the format, x uses base 16, and 1 means to print one byte per block. The -Ax says to print out the offsets in base 16 instead of the default base 8.

It does print out the offset of the end of the file as the last line, but that's trivial to get rid of with head -n -1 if not needed. There doesn't seem to be a way to make it use upper-case hex digits, but that's also easily fixable if you prefer them:

$ od -Ax -t x1 foo.bin | head -n -1 | tr a-f A-F
000000 4D 5A 90 00 03 00 00 00 04 00 00 00 FF FF 00 00

Upvotes: 2

Related Questions