Skip to content

Instantly share code, notes, and snippets.

@JCash
Created July 10, 2019 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JCash/f7a149e7565cc4dcc632f303d591a44d to your computer and use it in GitHub Desktop.
Save JCash/f7a149e7565cc4dcc632f303d591a44d to your computer and use it in GitHub Desktop.
Create C/C++ embeddable header from binary file
#! /usr/bin/env python
import sys, os
def Usage():
print "Usage: ./binary2header.py <file>"
if __name__ == '__main__':
if len(sys.argv) < 2:
Usage()
sys.exit(1)
path = sys.argv[1]
if not os.path.exists(path):
print "File does not exist:", path
sys.exit(1)
if not os.path.isfile(path):
print "Path is not a file:", path
sys.exit(1)
with open(path, 'rb') as f:
data = f.read()
name = os.path.basename(path).replace('.', '_').upper()
print "// Generated from: " + os.path.basename(path)
print "#pragma once"
print "const size_t %s_LEN = %d;" % (name, len(data))
print "const char %s_DATA[] = {" % name
step = 16
count = 0
for i in xrange(0, len(data), step):
chunk = data[i:i+step]
bchunk = ["'%02X'" % ord(c) for c in chunk]
print " ", ','.join(bchunk) + ("" if len(chunk) < step else ",")
count += step
print "};"
print ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment