bin2code.py 811 B

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/python3
  2. '''
  3. # Example:
  4. > python bin2code.py m5_logo.jpg
  5. > Out:m5_logo.jpg.c Done!
  6. '''
  7. import sys, os
  8. in_name = sys.argv[1]
  9. out_name = in_name + '.c'
  10. file_size = os.path.getsize(in_name)
  11. with open(in_name, 'rb') as infile:
  12. with open(out_name, 'wb+') as outfile:
  13. arrary_name = 'const unsigned char ' + out_name[0:out_name.find('.')] + '[' +str(file_size)+'] = {\n'
  14. outfile.write(arrary_name.encode('utf-8'))
  15. while True:
  16. data = infile.read(20)
  17. if len(data) > 0:
  18. # outfile.write('\t'.encode('utf-8'))
  19. for i in range(0, len(data)):
  20. d = "0x%02x," % data[i]
  21. outfile.write(d.encode('utf-8'))
  22. outfile.write('\n'.encode('utf-8'))
  23. else:
  24. outfile.write('};\n'.encode('utf-8'))
  25. break
  26. print('Out:'+ out_name +' Done!')