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

Hexify is a hex dump utility handy for viewing binary files at the command-prompt.

Python, 179 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import sys, os, traceback, getopt 
from types import *

class Display:
	def __init__(self):
		# display stuff
		self.clear		= ''
		self.lines_per_page	= 19
		self.chars_per_line	= 16
		self.oddity		= '.'
		
		self.line_width		= self.chars_per_line * 4 + 10
		self.dash		= '-' * self.line_width

		# other properties
		self.n_lines		= 0
		self.offset		= 0
		self.hand 		= -1
		
	def SetClear(self):
		# platform-dependent command to clear the display
		if sys.platform in ('linux-i386', 'linux2'):
			self.clear = 'clear'
		elif sys.platform in ('win32', 'dos', 'ms-dos'):
			self.clear = 'cls'
		
	def Clear(self):
		# clear screen using system command
		if self.clear:
			os.system(self.clear)
	
	def Header(self):
		# print header
		self.n_lines = 0
		self.Clear()
		print self.file
		print self.dash

	def Footer(self):
		# print footer
		print self.dash
		spacer = ' ' * (self.line_width - 27)
		s = raw_input(spacer + 'jump to... ')
		
		# if entry is...
		#   valid hex --> jump to that position
		#   x, q...   --> quit
		if s:
			s = s.lower().strip()
			if s in ('x', 'q', 'quit', 'exit', 'end'):
				raise 'MyDone'
			for c in s:
				if c not in '0123456789abcdef':
					s = ''
					break
		if s:
			self.offset = eval('int(0x%s)' % s)
			self.hand.seek(self.offset)
		
	def MakeAscii(self, char):
		# ascii representation of character
		ascii = ord(char)
		if ascii < 32 or (ascii > 127 and ascii < 161):
			x = self.oddity
		else:
			x = char
		return x

	def MakeHex(self, char, length):
		# hex representation of character/integer
		if type(char) is StringType:
			char = ord(char)
		x = hex(char)[2:]
		while len(x) < length:
			x = '0' + x
		return x

	def PrintLine(self, l_hex, l_char):
		# output a line
		if len(l_char) > 0:
			while len(l_char) < 16:
				l_hex	+= '   '
				l_char	+= ' '
			print '%s:%s | %s' % (self.MakeHex(self.offset, 6), l_hex, l_char)
			self.offset += self.chars_per_line
			self.n_lines += 1

	def Process(self):
		l_hex, l_char, n_char = '', '', 0
		
		self.hand = open(self.file, 'rb')   
		self.Header()

		while 1:
			# read next character
			n_char += 1
			char = self.hand.read(1)
			if not char:
				break
			
			# accumulate hex and ascii representations
			l_hex	+= ' ' + self.MakeHex(char, 2)
			l_char	+= self.MakeAscii(char)
			
			# line done
			if n_char == self.chars_per_line:
				self.PrintLine(l_hex, l_char)
				
				l_hex, l_char, n_char = '', '', 0

				# end of page
				if self.n_lines == self.lines_per_page:
					self.Footer()
					self.Header()
		self.PrintLine(l_hex, l_char)
		
	def Args(self, args=[]):
		# process command-line options
		try:
			opts, args = getopt.getopt(args, 'hcl:', ['help', 'clear', 'lines='])
		except getopt.error, msg:
			raise 'MyArgError'

		if len(args) > 1:
			raise 'MyArgError'
		self.file = args[0]
		
		for o, a in opts:
			if o in ('-h', '--help'):
				raise 'MyUsage'
			if o in ('-c', '--clear'):
				self.SetClear()
			if o in ('-l', '--lines'):
				self.lines_per_page	= int(a)

def Usage():
	print """
hexify 1.01
(C) 2001 Robin Parmar <robin.escalation@ACM.org>

Displays a hex dump of specified file.
After each page, you are prompted:
* tap <enter> to continue
* type <q>, <quit>, <x>, or <exit> to bail out
* type in hex code to jump to that location

"I want to hexify!"

usage:
python hexify.py [-h] [--help] [-c] [--clear] [-l<n>] [--lines=<n>] <file>

-h or --help: prints this message
-c or --clear: clears screen between pages (if supported)
-l or --lines: specifies number of lines per page
"""
    
if __name__ == '__main__':
	# this program is designed to run from the command-line
	code = 0
	try:
		d = Display()
		d.Args(sys.argv[1:])
		d.Process()
	except 'MyArgError':
		print '\n[incorrect command-line options]'
		Usage()
		code = 1
	except 'MyUsage':
		print '\n[requested usage info]'
		Usage()
	except 'MyDone':
		print '\n[interrupted by user]'
	except KeyboardInterrupt:
		print '\n[interrupted by user]'
	except:
		# unexpected error
		traceback.print_exc()
		code = 2
	sys.exit(code)

Hexify can be seen as an alternative or improvement to Tony Dycks' readbin.py. It is more compact, more Pythonic, and slightly more feature-rich (command-line parameters, exit codes, jump-to location, etc). I have kept his output format and platform-dependent display clearing.

By implementing the bulk of the functionality as a class, the code can be more-readily adapted to other display environment. I would like an HTML-friendly version, for example. Other possible enhancements include adding a parameter to specify a display range.

This code demonstrates argument processing, data type conversion, exception handling, raw input, and some rudimentary file handling.

CHANGE: A typo had the file opening in text mode. This has been fixed.