-
Notifications
You must be signed in to change notification settings - Fork 0
/
bin2mif.py
106 lines (85 loc) · 2.47 KB
/
bin2mif.py
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
import sys
import numpy as np
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
DEBUG = 0
def parsefile(filename, wordsize):
dump = []
read_data = None
with open(filename, "rb") as inputfile:
read_data = np.fromfile(inputfile, dtype=np.uint8)
wordsizeinbytes = wordsize / 8
wordcounter = 0
count = 0
tempstring = ""
for byte in read_data:
s = hex(byte)[2:]
if len(s) % 2 != 0:
s = "0" + s
tempstring += s
count = (count + 1) % wordsizeinbytes
if count == 0:
dump.append(tempstring)
tempstring = ""
wordcounter += 1
return [dump, wordcounter]
def writefile(filename, wordsize, data):
f = open(filename, "w")
f.write("WIDTH=")
f.write(str(wordsize))
f.write(";\n")
f.write("DEPTH=")
f.write(str(len(data)))
f.write(";\n\n")
f.write("ADDRESS_RADIX=HEX;\nDATA_RADIX=HEX;\n\nCONTENT BEGIN\n")
for i in range(0, len(data)):
f.write("\t")
f.write(hex(i)[2:])
f.write(" : ")
f.write(data[i])
f.write(";\n")
f.write("END;\n")
def main(argv=None):
if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)
try:
# Setup argument parser
parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter)
parser.add_argument(
dest="inputfile",
help="path to input file [default: %(default)s]",
metavar="inputfile",
)
parser.add_argument(
dest="outputfile",
help="path to output file [default: %(default)s]",
metavar="outputfile",
)
parser.add_argument(
dest="wordsize",
help="size of wordsize [default: %(default)s]",
metavar="wordsize",
nargs="?",
default=8,
)
# Process arguments
args = parser.parse_args()
inputfile = args.inputfile
outputfile = args.outputfile
wordsize = int(args.wordsize)
print("input:", inputfile)
print("output:", outputfile)
print("wordsize:", wordsize)
result = parsefile(inputfile, wordsize)
writefile(outputfile, wordsize, result[0])
return 0
except KeyboardInterrupt:
return 0
except Exception as e:
if DEBUG:
raise (e)
return 2
if __name__ == "__main__":
sys.exit(main())