Welcome, guest | Sign In | My Account | Store | Cart

Hex dump a sequence of bytes.

Sample output:

 0000000000: 33 C0 8E D0 BC 00 7C 8E  C0 8E D8 BE 00 7C BF 00  3.....|. .....|..
 0000000010: 06 B9 00 02 FC F3 A4 50  68 1C 06 CB FB B9 04 00  .......P h.......
 0000000020: BD BE 07 80 7E 00 00 7C  0B 0F 85 0E 01 83 C5 10  ....~..| ........
 0000000030: E2 F1 CD 18 88 56 00 55  C6 46 11 05 C6 46 10 00  .....V.U .F...F..
 0000000040: B4 41 BB AA 55 CD 13 5D  72 0F 81 FB 55 AA 75 09  .A..U..] r...U.u.
 0000000050: F7 C1 01 00 74 03 FE 46  10 66 60 80 7E 10 00 74  ....t..F .f`.~..t
 0000000060: 26 66 68 00 00 00 00 66  FF 76 08 68 00 00 68 00  &fh....f .v.h..h.
 0000000070: 7C 68 01                                          |h.
Python, 16 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def group(a, *ns):
    for n in ns:
        a = [a[i:i+n] for i in xrange(0, len(a), n)]
    return a

def join(a, *cs):
    return [cs[0].join(join(t, *cs[1:])) for t in a] if cs else a

def hexdump(data):
    toHex = lambda c: '{:02X}'.format(ord(c))
    toChr = lambda c: c if 32 <= ord(c) < 127 else '.'
    make = lambda f, *cs: join(group(map(f, data), 8, 2), *cs)
    hs = make(toHex, '  ', ' ')
    cs = make(toChr, ' ', '')
    for i, (h, c) in enumerate(zip(hs, cs)):
        print '{:010X}: {:48}  {:16}'.format(i * 16, h, c)

2 comments

Antoni Gual 8 years, 10 months ago  # | flag

Won't work in windows 3 as map does'nt return a list anyomore.

Antoni Gual 8 years, 9 months ago  # | flag

This works in python3

def group(a, *ns):
  for n in ns:
    a = [a[i:i+n] for i in range(0, len(a), n)]
  return a

def join(a, *cs):
  return [cs[0].join(join(t, *cs[1:])) for t in a] if cs else a

def hexdump(data):
  toHex = lambda c: '{:02X}'.format(c)
  toChr = lambda c: chr(c) if 32 <= c < 127 else '.'
  make = lambda f, *cs: join(group(list(map(f, data)), 8, 2), *cs)
  hs = make(toHex, '  ', ' ')
  cs = make(toChr, ' ', '')
  for i, (h, c) in enumerate(zip(hs, cs)):
    print ('{:010X}: {:48}  {:16}'.format(i * 16, h, c))


with (open ('tohex.py','br')) as file:
  data=file.read()
  hexdump(data)
Created by Wenlong Liu on Fri, 29 May 2015 (MIT)
Python recipes (4591)
Wenlong Liu's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks