|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import os |
| 5 | +import struct |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +def print_preamble(output_file, from_string): |
| 10 | + print(f'\ |
| 11 | +/*\r\n\ |
| 12 | + * File automatically generated by: {Path(__file__).name}\r\n\ |
| 13 | + * From binary: {from_string}\r\n\ |
| 14 | + */\r\n\ |
| 15 | +\n\ |
| 16 | +#pragma once\r\n\ |
| 17 | +\n', file=output_file, end='') |
| 18 | + |
| 19 | + |
| 20 | +def print_array(output_file, name, byte_array): |
| 21 | + print(f'static const uint8_t {name}[] = ', file=output_file, end='{\r\n\t') |
| 22 | + |
| 23 | + num_bytes = sum(1 for byte in byte_array) |
| 24 | + |
| 25 | + for i in range(num_bytes): |
| 26 | + if (i + 1) % 16 == 0: |
| 27 | + print(f'0x{byte_array[i]:02X},', file=output_file, end='\r\n\t') |
| 28 | + elif (i + 1) == num_bytes: |
| 29 | + print(f'0x{byte_array[i]:02X}', file=output_file, end='};\r\n') |
| 30 | + else: |
| 31 | + print(f'0x{byte_array[i]:02X}, ', file=output_file, end='') |
| 32 | + |
| 33 | + |
| 34 | +if __name__ == '__main__': |
| 35 | + parser = argparse.ArgumentParser(description='Format binary file to C header') |
| 36 | + parser.add_argument('-o', '--output', type=str, |
| 37 | + help='Output file.') |
| 38 | + parser.add_argument('binary', metavar='binary.bin', type=str, |
| 39 | + help='binary to parse.') |
| 40 | + args = parser.parse_args() |
| 41 | + |
| 42 | + if not args.binary or not os.path.exists(args.binary): |
| 43 | + print(f'{args.binary} doesn\'t exist', file=sys.stderr) |
| 44 | + exit(1) |
| 45 | + |
| 46 | + try: |
| 47 | + binary = open(args.binary, 'rb') |
| 48 | + except PermissionError as e: |
| 49 | + print(f'can\'t open {args.binary}: {str(e)}', file=sys.stderr) |
| 50 | + exit(1) |
| 51 | + |
| 52 | + if args.output: |
| 53 | + output_file = args.output |
| 54 | + else: |
| 55 | + output_file = Path(args.binary).stem + '.h' |
| 56 | + |
| 57 | + try: |
| 58 | + output = open(output_file, 'wt') |
| 59 | + except PermissionError as e: |
| 60 | + print(f'can\'t open {output_file}: {str(e)}', file=sys.stderr) |
| 61 | + exit(1) |
| 62 | + |
| 63 | + num_bytes = os.path.getsize(args.binary) |
| 64 | + binary_bytes = bytearray(binary.read(num_bytes)) |
| 65 | + |
| 66 | + print_preamble(output, Path(args.binary).name) |
| 67 | + print_array(output, Path(args.binary).stem, binary_bytes) |
0 commit comments