file-hex-array.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import binascii
  2. import os.path
  3. import sys
  4. def tof(filepath):
  5. with open(filepath, 'r') as f:
  6. content = f.read()
  7. content = content.replace("0x", "")
  8. content = content.split(',')
  9. for i in range(len(content)):
  10. if len(content[i]) == 1:
  11. content[i] = "0" + content[i]
  12. content = "".join(content)
  13. with open(filepath + ".file", 'wb') as f:
  14. content = f.write(content.decode("hex"))
  15. print(os.path.basename(filepath) + ".file created.")
  16. exit(0)
  17. def toa(filepath):
  18. with open(filepath, 'rb') as f:
  19. content = f.read()
  20. content = binascii.hexlify(content)
  21. content = [content[i:i + 2] for i in range(0, len(content), 2)]
  22. content = ",0x".join(content)
  23. content = "0x" + content
  24. content = content.replace("0x00", "0x0")
  25. with open(filepath + ".array", 'w') as f:
  26. content = f.write(content)
  27. print(os.path.basename(filepath) + ".array created.")
  28. exit(0)
  29. def usage():
  30. print("========================================================\n\
  31. #\n\
  32. # Usage: python file-hex-array.py [action] [option]\n\
  33. #\n\
  34. # Arguments:\n\
  35. # action ==> toa # convert file to array [option is file path]\n\
  36. # tof # convert array to file [option is array file path]\n\
  37. #\n\
  38. # Example : python file-hex-array.py toa 1.png\n\
  39. #\n\
  40. ========================================================")
  41. exit(1)
  42. if len(sys.argv) != 3:
  43. usage()
  44. if sys.argv[1] == "toa" and os.path.isfile(sys.argv[2]):
  45. toa(sys.argv[2])
  46. elif sys.argv[1] == "tof" and os.path.isfile(sys.argv[2]):
  47. tof(sys.argv[2])
  48. else:
  49. usage()