-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoding_to_bytes.py
More file actions
72 lines (65 loc) · 2.48 KB
/
encoding_to_bytes.py
File metadata and controls
72 lines (65 loc) · 2.48 KB
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
import optparse
import os
import sys
def main():
parser = optparse.OptionParser(
usage="usage: %prog [options] file1 [file2 [... fileN]]")
parser.add_option("-b", "--blocksize", dest="blocksize", type="int",
help="block size (8..80) [default: %default]")
parser.add_option("-d", "--decimal", dest="decimal",
action="store_true",
help="decimal block numbers [default: hexadecimal]")
parser.add_option("-e", "--encoding", dest="encoding",
help="encoding (ASCII..UTF-32) [default: %default]")
parser.set_defaults(blocksize=16, decimal=False, encoding="UTF-8")
opts, files = parser.parse_args()
if not (8 <= opts.blocksize <= 80):
parser.error("invalid blocksize")
if not files:
parser.error("no files specified")
for a, filename in enumerate(files):
if a:
print()
if len(files) > 1:
print("File:", filename)
encodeToBytes(filename, opts.blocksize, opts.encoding, opts.decimal)
def encodeToBytes(filename, blocksize, encoding, decimal):
encoding_text = "{0} characters".format(encoding.upper())
width = (blocksize * 2) + (blocksize // 4)
if blocksize % 4:
width += 1
print("Block Bytes{0:{1}} {2}".format("", (width - 5),
encoding_text))
print("-------- {0} {1}".format("-" * (width - 1),
"-" * max(len(encoding_text), blocksize)))
block_number_format = "{0:08} " if decimal else "{0:08X} "
block_number = 0
myFile = None
try:
myFile = open(filename, "rb")
while True:
data = myFile.read(blocksize)
if not data:
break
line = [block_number_format.format(block_number)]
chars = []
for a, x in enumerate(data):
if a % 4 == 0:
line.append(" ")
line.append("{0:02X}".format(x))
chars.append(x if 32 <= x < 127 else ord("."))
for a in range(len(data), blocksize):
if a % 4 == 0:
line.append(" ")
line.append(" ")
line.append(" ")
line.append(bytes(chars).decode(encoding, "replace")
.replace("\uFFFD", "."))
print("".join(line))
block_number += 1
except EnvironmentError as err:
print(err)
finally:
if myFile is not None:
myFile.close()
main()