Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/python
- # coding: utf-8
- # datconv.py
- import sys, re, argparse
- def str2byt(x):
- done = False
- out = b''
- byte = 0
- for nybble in x:
- if not done:
- byte = int( nybble, 16 )
- byte <<= 4
- else:
- byte |= ( int( nybble, 16 ) & 0xF )
- out = out + bytes([byte])
- done = not done
- return out
- hx1 = lambda n: hex(n)[2:].zfill(2)
- REGEX_DEC = re.compile(r'^ d[bw] ((?:[0-9]{3},?)+)\s*(?:;.*)?$')
- REGEX_HEX = re.compile(r'^ d[bw] ((?:0(?:[A-Fa-f0-9]{2})+h,?)+)\s*(?:;.*)?$')
- def divhx(x):
- pcs = []
- for i in range(len(x) // 2):
- pcs.append(x[i*2:i*2+2])
- return ''.join(pcs[::-1])
- def divhxl(x):
- out = ''
- for k in x:
- out += divhx(k)
- return out
- def Main(args):
- txt = open(args.filein, 'r').read()
- v = not args.quiet
- lins = txt.split('\n')
- if args.guess:
- r1 = REGEX_DEC
- r2 = REGEX_HEX
- for i in range(len(lins)):
- if r1.match(lins[i]):
- args.decimal = True
- break
- elif r2.match(lins[i]):
- args.decimal = False
- break
- else:
- raise Exception
- if args.decimal:
- reg = REGEX_DEC
- else:
- reg = REGEX_HEX
- datout = ''
- uuct = 0
- for i,l in enumerate(lins):
- mm = reg.match(l)
- if mm:
- cur_dats = mm.groups()[0].split(',')
- if args.decimal:
- cur_dats_2 = [hx1(int(x[1:-1])) for x in cur_dats]
- else:
- cur_dats_2 = [x[1:-1] for x in cur_dats]
- datout += ''.join(cur_dats_2)
- else:
- if v:
- print('Line does not match pattern:')
- print(i+1, l)
- uuct += 1
- if uuct > 10:
- input()
- uuct = 0
- open(args.fileout, 'wb').write(str2byt(datout))
- if __name__ == '__main__':
- parser = argparse.ArgumentParser(description='converts pokesource data to bin')
- parser.add_argument('filein', type=str, help='file in')
- parser.add_argument('fileout', type=str, help='file out')
- parser.add_argument('-q', dest='quiet', action='store_true', help='quiet')
- parser.add_argument('-d', dest='decimal', action='store_true', help='data is decimal')
- parser.add_argument('-g', dest='guess', action='store_true', help='guess hex or dec')
- args = parser.parse_args()
- Main(args)
- #
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement