Last active
January 18, 2021 08:24
-
-
Save captainGeech42/51d8d73bff43d5c4fac593ef7b033fad to your computer and use it in GitHub Desktop.
Dump a binary file as a C-style array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
def main(argv): | |
if len(argv) == 1: | |
print(f"usage: {argv[0]} [path to bin file]") | |
return 1 | |
with open(argv[1], "rb") as f: | |
data = f.read() | |
data_len = len(data) | |
name = argv[1].split(".")[0] | |
print(f"unsigned char {name}[] = {{") | |
for i in range(data_len): | |
# check if we need to indent | |
if i % 8 == 0: | |
print(" ", end="") | |
# print byte | |
# this jank line ensures every byte is 0x__, instead of bytes < 0x10 being 0x_ | |
print(f"0x{hex(data[i])[2:].ljust(2, '0')}", end="") | |
# check if we need a comma | |
if i + 1 != data_len: | |
print(",", end="") | |
# check if we need a newline | |
# if no newline, append a comma | |
if (i + 1) % 8 == 0 or i + 1 == data_len: | |
print("") | |
else: | |
print(" ", end="") | |
print("};") | |
print(f"\nunsigned int {name}_len = {data_len};") | |
return 0 | |
if __name__ == "__main__": | |
sys.exit(main(sys.argv)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment