file-hex-array.py 1.6 KB

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