2014-12-15 15:19:55 +01:00
|
|
|
#!/usr/bin/python
|
2015-05-07 10:52:45 +02:00
|
|
|
##
|
|
|
|
## license:BSD-3-Clause
|
|
|
|
## copyright-holders:Aaron Giles, Andrew Gardner
|
2014-12-15 15:19:55 +01:00
|
|
|
|
2015-01-08 01:29:24 +01:00
|
|
|
from __future__ import with_statement
|
|
|
|
|
2014-12-15 15:19:55 +01:00
|
|
|
import sys
|
|
|
|
import os
|
|
|
|
|
2015-03-05 16:38:07 +01:00
|
|
|
if len(sys.argv) < 4:
|
2014-12-15 15:19:55 +01:00
|
|
|
print('Usage:')
|
|
|
|
print(' file2str <source.lay> <output.h> <varname> [<type>]')
|
|
|
|
print('')
|
|
|
|
print('The default <type> is char, with an assumed NULL terminator')
|
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
terminate = 1
|
|
|
|
srcfile = sys.argv[1]
|
|
|
|
dstfile = sys.argv[2]
|
|
|
|
varname = sys.argv[3]
|
|
|
|
|
2015-03-05 16:38:07 +01:00
|
|
|
if len(sys.argv) >= 5:
|
2014-12-15 15:19:55 +01:00
|
|
|
type = sys.argv[4]
|
|
|
|
terminate = 0
|
|
|
|
else:
|
|
|
|
type = 'char'
|
|
|
|
|
|
|
|
try:
|
|
|
|
myfile = open(srcfile, 'rb')
|
|
|
|
except IOError:
|
2015-03-06 00:04:37 +01:00
|
|
|
sys.stderr.write("Unable to open source file '%s'\n" % srcfile)
|
2014-12-15 15:19:55 +01:00
|
|
|
sys.exit(-1)
|
|
|
|
|
2015-03-03 10:16:05 +01:00
|
|
|
byteCount = os.path.getsize(srcfile)
|
2014-12-15 15:19:55 +01:00
|
|
|
try:
|
|
|
|
dst = open(dstfile,'w')
|
2015-03-05 16:38:07 +01:00
|
|
|
dst.write('extern const %s %s[];\n' % ( type, varname ))
|
|
|
|
dst.write('const %s %s[] =\n{\n\t' % ( type, varname))
|
2014-12-15 15:19:55 +01:00
|
|
|
offs = 0
|
|
|
|
with open(srcfile, "rb") as src:
|
|
|
|
while True:
|
|
|
|
chunk = src.read(16)
|
|
|
|
if chunk:
|
|
|
|
for b in chunk:
|
2015-03-03 17:12:30 +01:00
|
|
|
# For Python 2.x compatibility.
|
|
|
|
if isinstance(b, str):
|
|
|
|
b = ord(b)
|
|
|
|
dst.write('0x%02x' % b)
|
2015-03-05 16:38:07 +01:00
|
|
|
offs += 1
|
2015-03-03 10:16:05 +01:00
|
|
|
if offs != byteCount:
|
2014-12-15 16:46:04 +01:00
|
|
|
dst.write(',')
|
2014-12-15 15:19:55 +01:00
|
|
|
else:
|
|
|
|
break
|
2015-03-03 10:16:05 +01:00
|
|
|
if offs != byteCount:
|
2014-12-15 15:19:55 +01:00
|
|
|
dst.write('\n\t')
|
|
|
|
if terminate == 1:
|
2014-12-15 16:46:04 +01:00
|
|
|
dst.write(',0x00')
|
2014-12-15 15:19:55 +01:00
|
|
|
dst.write('\n};\n')
|
|
|
|
dst.close()
|
|
|
|
except IOError:
|
2015-03-06 00:04:37 +01:00
|
|
|
sys.stderr.write("Unable to open output file '%s'\n" % dstfile)
|
2015-01-08 01:29:24 +01:00
|
|
|
sys.exit(-1)
|