hex2bin.py 898 B

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/env python
  2. # This Source Code Form is subject to the terms of the Mozilla Public
  3. # License, v. 2.0. If a copy of the MPL was not distributed with this
  4. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. import sys
  6. import os
  7. from io import open
  8. import binascii
  9. import re
  10. def clean_line(string):
  11. comment_re = re.compile("/\*.*?\*/") # matches C-style comments /* */ at the end of a line
  12. return re.sub(comment_re, "" ,string).replace(" ","").replace("\n","")
  13. if len(sys.argv) < 2:
  14. print("Usage: python hex2bin.py file1.hex file2.hex ...")
  15. exit(0)
  16. filenames = sys.argv[1:]
  17. for f in filenames:
  18. bn = os.path.basename(f)
  19. with open(f, mode="rt") as ff:
  20. with open(bn[:-4] + ".bin", "wb") as out:
  21. lines = ff.readlines()
  22. for l in lines:
  23. c = clean_line(l)
  24. out.write(binascii.unhexlify(c))