Simple Binary Viewer

With this simple Python script it is possible to view a binary file in different styles. This is also possible for example with the Linux tool hexdump. Nevertheless it is sometimes necessary to have this code in an own tool.

$./binaryview.py | less
ADDRESS    | BIN                                 | HEX         | ASCII
-----------+-------------------------------------+-------------+---------
0x00000000 | 00000001 00000000 00000000 00000000 | 01 00 00 00 | . . . .
0x00000004 | 01010100 01010000 00101101 01001100 | 54 50 2d 4c | T P - L
0x00000008 | 01001001 01001110 01001011 00100000 | 49 4e 4b 20 | I N K .
0x0000000c | 01010100 01100101 01100011 01101000 | 54 65 63 68 | T e c h

To use this script create a file for example binaryview.py and add the script content below. The standard name of the ibnary file is test.img, which can be changed in the Python script.

#!/usr/bin/env python
import string

imgname ="test.img"
addresscnt = 0
print "ADDRESS    | BIN                                 | HEX         | ASCII"
print "-----------+-------------------------------------+-------------+---------"
with open(imgname, 'rb') as f:
   for chunk in iter(lambda: f.read(4), b''):
      byte0 = chunk[0]
      byte1 = chunk[1]
      byte2 = chunk[2]
      byte3 = chunk[3]
      print "0x" + hex(addresscnt)[2:].zfill(8) \
         + " | " \
         + bin(ord(byte0))[2:].zfill(8)+ " " \
         + bin(ord(byte1))[2:].zfill(8) + " " \
         + bin(ord(byte2))[2:].zfill(8) + " " \
         + bin(ord(byte3))[2:].zfill(8) \
         + " | "             \
         + hex(ord(byte0))[2:].zfill(2) + " " \
         + hex(ord(byte1))[2:].zfill(2) + " " \
         + hex(ord(byte2))[2:].zfill(2) + " " \
         + hex(ord(byte3))[2:].zfill(2) \
         + " |",
      if ord(byte0) > 32 and ord(byte0) < 128:
         print byte0,
      else:
         print ".",
      if ord(byte1) > 32 and ord(byte1) < 128:
         print byte1,
      else:
         print ".",
      if ord(byte2) > 32 and ord(byte2) < 128:
         print byte2,
      else:
         print ".",
      if ord(byte3) > 32 and ord(byte3) < 128:
         print byte3
      else:
         print "."
      addresscnt = addresscnt + 4

After that it can be executed and for exampled piped into less.

./binaryview.py | less

Leave a Reply

Your email address will not be published. Required fields are marked *

*