Skip to content

Instantly share code, notes, and snippets.

@amir-saniyan
Last active August 23, 2020 17:48
Show Gist options
  • Save amir-saniyan/c83b0993f067728446f00593f52955f1 to your computer and use it in GitHub Desktop.
Save amir-saniyan/c83b0993f067728446f00593f52955f1 to your computer and use it in GitHub Desktop.
This code converts any file to C++ header file.

File To Header

This code converts any file to C++ header file.

Usage

usage: file_to_header.py [-h] -i INPUT -o OUTPUT -n NAME [-k KEY]

Converts any file to C++ header file.

optional arguments:
  -h, --help            show this help message and exit
  -i INPUT, --input INPUT
                        Input file name
  -o OUTPUT, --output OUTPUT
                        Output file name
  -n NAME, --name NAME  Variable name
  -k KEY, --key KEY     XOR key

Example

$ python3 file_to_header.py --input input.txt --output output.h --name DATA

input.txt:

Hello World

output.h:

/* Auto generated file. */
const unsigned char DATA[] =
{
	0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64
};
import argparse
COLUMNS = 16
def main():
argument_parser = argparse.ArgumentParser(description='Converts any file to C++ header file.')
argument_parser.add_argument('-i', '--input', type=str, required=True, help='Input file name')
argument_parser.add_argument('-o', '--output', type=str, required=True, help='Output file name')
argument_parser.add_argument('-n', '--name', type=str, required=True, help='Variable name')
argument_parser.add_argument('-k', '--key', type=str, required=False, default='', help='XOR key')
args = argument_parser.parse_args()
input_file_name = args.input
output_file_name = args.output
variable_name = args.name
xor_key = bytes(args.key, 'utf-8')
header = '/* Auto generated file. */\n'
header += 'const unsigned char {0}[] =\n'.format(variable_name)
header += '{'
index = 0
with open(input_file_name, 'rb') as input_file:
byte = input_file.read(1)
while byte != b'':
if index % COLUMNS == 0:
header += '\n\t'
if len(xor_key) != 0:
v1 = int.from_bytes(byte, byteorder='little')
v2 = xor_key[index % len(xor_key)]
v = v1 ^ v2
byte = bytes([v])
header += '0x{0}, '.format(byte.hex())
byte = input_file.read(1)
index += 1
if header.endswith(', '):
header = header[:-2]
header += '\n};\n'
with open(output_file_name, 'w') as output_file:
output_file.write(header)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment