Jukka Rissanen | 0ff4c25 | 2017-09-13 10:43:30 +0300 | [diff] [blame] | 1 | #!/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 | |
| 11 | import argparse |
| 12 | import codecs |
| 13 | import gzip |
| 14 | import io |
| 15 | |
| 16 | def 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 | |
| 27 | def get_nice_string(list_or_iterator): |
| 28 | return ", ".join( "0x" + str(x) for x in list_or_iterator) |
| 29 | |
| 30 | def 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 | |
| 35 | def 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 | |
| 48 | if __name__ == "__main__": |
| 49 | main() |