blob: 6c7cdfc855205e233f79fa130d5744f7c8cf6af7 [file] [log] [blame]
Jukka Rissanen0ff4c252017-09-13 10:43:30 +03001#!/usr/bin/env python3
2#
3# Copyright (c) 2017 Intel Corporation
4#
5# SPDX-License-Identifier: Apache-2.0
6
7# This converts a file to a list of hex characters which can then
8# be included to a source file.
9# Optionally, the output can be compressed if needed.
10
11import argparse
12import codecs
13import gzip
14import io
15
16def parse_args():
17 global args
18
19 parser = argparse.ArgumentParser(description = __doc__,
20 formatter_class = argparse.RawDescriptionHelpFormatter)
21
22 parser.add_argument("-f", "--file", required=True, help="Input file")
23 parser.add_argument("-g", "--gzip", action="store_true",
24 help="Compress the file using gzip before output")
25 args = parser.parse_args()
26
27def get_nice_string(list_or_iterator):
28 return ", ".join( "0x" + str(x) for x in list_or_iterator)
29
30def make_hex(chunk):
31 hexdata = codecs.encode(chunk, 'hex').decode("utf-8")
32 hexlist = map(''.join, zip(*[iter(hexdata)]*2))
33 print(get_nice_string(hexlist) + ',')
34
35def main():
36 parse_args()
37
38 if args.gzip:
39 with open(args.file, 'rb') as fg:
40 content = io.BytesIO(gzip.compress(fg.read(), compresslevel=9))
41 for chunk in iter(lambda: content.read(8), b''):
42 make_hex(chunk)
43 else:
44 with open(args.file, "rb") as fp:
45 for chunk in iter(lambda: fp.read(8), b''):
46 make_hex(chunk)
47
48if __name__ == "__main__":
49 main()