-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhex2bin.py
81 lines (63 loc) · 1.8 KB
/
hex2bin.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
#!/usr/bin/env python
#coding:utf-8
#
import traceback
import sys
try:
from optparse import OptionParser
except:
exit(1)
def hexstr2bin(hexdata, output_file):
if None == hexdata:
print("no input")
return
length = len(hexdata)
if length == 0:
print("empty input")
return
count = 0
n = 0
result = ""
for c in hexdata:
tmp = None
if c >= '0' and c <= '9':
tmp = ord(c) - ord('0')
elif c >= 'A' and c <= 'F':
tmp = ord(c) - ord('A') + 10
elif c >= 'a' and c <= 'f':
tmp = ord(c) - ord('a') + 10
if None == tmp:
continue
if count % 2 == 0:
n = tmp << 4
else:
result += chr(n | tmp)
n = 0
count += 1
if count % 2 != 0:
print("invalid input hex data, count is " + str(count))
return
output_file.write(result)
#print("valid character number is " + str(count) + ", result size " + str(len(result)))
if __name__ == "__main__":
try:
options_parser = OptionParser()
options_parser.add_option('-x', '--hex', action='store', type='string',
dest='hexdata', default=None, help='data string in hex format')
options_parser.add_option('-f', '--file', action='store', type='string',
dest='file', default=None, help='file with hex data')
options_parser.add_option('-o', '--output', action='store', type='string',
dest='output', default='output.txt', help='output file')
(options, args) = options_parser.parse_args(sys.argv[1:])
with open(options.output, 'wb') as output_file:
if options.file != None:
with open(options.file, 'rb') as source_file:
for line in source_file.readlines():
hexstr2bin(line, output_file)
else:
hexstr2bin(options.hexdata, output_file)
except Exception as ex:
print("exception: " + str(ex))
traceback.print_exc()
exit(1)
exit(0)