-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathdecode_buffer.py
executable file
·83 lines (70 loc) · 2.04 KB
/
decode_buffer.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
#!/usr/bin/env python3
import sys, os, struct, itertools, io
import argparse
try:
import float_to_hex
except ImportError:
float_to_hex = None
def dump(stream, args):
last_non_zero = 0
if args.truncate:
out = io.StringIO()
else:
out = sys.stdout
if args.offset:
stream.seek(args.offset)
for index in itertools.count():
zero = True
for offset in range(args.stride // 4):
if args.length and args.length <= index * args.stride + offset * 4:
return
buf = stream.read(4)
if len(buf) == 0:
return
if len(buf) < 4:
print('Remaining:', repr(buf), file=out)
return
if float_to_hex is not None:
fval, = struct.unpack('<I', buf)
fval = float_to_hex.hex_to_best_float_str(fval)
else:
fval, = struct.unpack('<f', buf)
ival, = struct.unpack('<i', buf)
uval, = struct.unpack('<I', buf)
if uval:
zero = False
if args.stride == 4:
print('{:08x}: '.format((index * args.stride + offset * 4)), end='', file=out)
else:
print('%d+%-4s ' % (index, '%d:' % (offset * 4)), end='', file=out)
if args.format == 'int':
print('{}'.format(ival), file=out)
elif args.format == 'float':
print('{}'.format(fval), file=out)
else:
print('0x{:08x} | {: 12d} | {}'.format(uval, ival, fval), file=out)
if args.truncate and not zero:
print(out.getvalue(), end='')
out.seek(0)
out.truncate(0)
if args.stride != 4:
print(file=out)
def parse_offset(off):
if off.lower().startswith('0x'):
return int(off, 16)
return int(off)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='+', type=argparse.FileType('rb'))
parser.add_argument('-s', '--stride', type=int, default=4)
parser.add_argument('-t', '--truncate', action='store_true')
parser.add_argument('-o', '--offset', type=parse_offset)
parser.add_argument('-l', '--length', type=parse_offset)
parser.add_argument('-f', '--format', choices=('int', 'float'))
args = parser.parse_args()
for file in args.files:
print()
print(file.name)
dump(file, args)
if __name__ == '__main__':
main()