From a2ad755b1cfc9487fcf57971040ecdf537b64c12 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Sun, 23 Jan 2022 00:39:38 +0000 Subject: [PATCH] Add script for converting arbitrary binary data to C arrays This is similar to the existing png2c, but works for any binary data, not just PNG files. Another small difference is that this script puts 16 bytes per line instead of 8 -- this still results in reasonably short lines, but twice shorter files, so seems to be worth it. --- misc/scripts/bin2c.py | 47 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100755 misc/scripts/bin2c.py diff --git a/misc/scripts/bin2c.py b/misc/scripts/bin2c.py new file mode 100755 index 0000000000..bd5d89d590 --- /dev/null +++ b/misc/scripts/bin2c.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# +# This is a slightly generalized version of bin2c.py and is based on it. + +import sys +import os +import os.path +import re +import array + +if len(sys.argv) < 2: + print("""Usage: bin2c binary_file... + +Output input files data as C arrays to standard output.""") + sys.exit(1) + +r = re.compile("^([a-zA-Z._][a-zA-Z._0-9]*)[.]([a-zA-Z_0-9]+)$") +for path in sys.argv[1:]: + filename = os.path.basename(path).replace('-','_') + m = r.match(filename) + + # Allow only filenames that make sense as C variable names + if not(m): + print("Skipped file (unsuitable filename): " + filename) + continue + + # Read file as character array + bytes = array.array('B', open(path, "rb").read()) + count = len(bytes) + + # Create the C header + text = "/* %s - %d bytes */\n" \ + "static const unsigned char %s_%s_data[] = {\n" % ( + filename, count, m.group(1), m.group(2)) + + i = 0 + for byte in bytes: + if i % 16 == 0: + text += "\n " + i += 1 + text += " 0x%02x" % byte + if i != count: + text += "," + + text += "\n};" + + print(text)