Skip to content

Instantly share code, notes, and snippets.

@rakete
Created November 22, 2016 17:52
Show Gist options
  • Save rakete/c6f7795e30d5daf43bb600abc06a9ef4 to your computer and use it in GitHub Desktop.
Save rakete/c6f7795e30d5daf43bb600abc06a9ef4 to your computer and use it in GitHub Desktop.
xxd -i like c include generator written in python
# -*- coding: utf-8 -*-
import os.path
import string
import sys
def xxd(file_path):
with open(file_path, 'r') as f:
array_name = file_path.replace('/','_').replace('.','_')
output = "unsigned char %s[] = {" % array_name
length = 0
while True:
buf = f.read(12)
if not buf:
output = output[:-2]
break
else:
output += "\n "
for i in buf:
output += "0x%02x, " % ord(i)
length += 1
output += "\n};\n"
output += "unsigned int %s_len = %d;" % (array_name, length)
print output
if __name__ == '__main__':
if not os.path.exists(sys.argv[1]):
print >> (sys.stderr, "The file doesn't exist.")
sys.exit(1)
xxd(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment