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

Load a file and print formatted hexadecimal and ascii characters to the console.

Python, 45 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
from string import ascii_letters, digits, punctuation

filename = r'i:\Python\test.file'
file = open(filename, 'rb')
data = file.read()
file.close()

bytesRead = len(data)

def bufferToHex(buffer, start, count):
    accumulator = ''
    for item in range(count):
        accumulator += '%02X' % buffer[start + item] + ' '
    return accumulator

def bufferToAscii(buffer, start, count):
    accumulator = ''
    for item in range(count):
        char = chr(buffer[start + item])
        if char in ascii_letters or \
           char in digits or \
           char in punctuation or \
           char == ' ':
            accumulator += char
        else:
            accumulator += '.'
    return accumulator

index = 0
size = 20
hexFormat = '{:'+str(size*3)+'}'
asciiFormat = '{:'+str(size)+'}'

print()
while index < bytesRead:
    
    hex = bufferToHex(data, index, size)
    ascii = bufferToAscii(data, index, size)

    print(hexFormat.format(hex), end='')
    print('|',asciiFormat.format(ascii),'|')
    
    index += size
    if bytesRead - index < size:
        size = bytesRead - index

This is just a little program I wrote while learning Python.

2 comments

Metal 13 years, 11 months ago  # | flag

A more little one:

print 'aaa'.encode('hex')
print 'aaa'.encode('hex').decode('hex')
Stephen Chappell 13 years, 9 months ago  # | flag

You may be interested in recipe 576945 if you want a short command-line hex-dumper.