Skip to content

Instantly share code, notes, and snippets.

@sokil
Last active May 3, 2026 21:17
Show Gist options
  • Select an option

  • Save sokil/8b77fea73271bb85a1a5c8c48eb0357c to your computer and use it in GitHub Desktop.

Select an option

Save sokil/8b77fea73271bb85a1a5c8c48eb0357c to your computer and use it in GitHub Desktop.
extract_cpp_hex_image.py

Command to create hex file:

xxd -i wallpaper.jpeg > wallpaper.h

Example:

extern const unsigned char wallpaper[];
extern const unsigned int wallpaper_len;
#!/usr/bin/env python3
"""Extract a binary image from a C/C++ header or source file containing a hex byte array."""
import re
import sys
from pathlib import Path
def extract(src: Path, out: Path) -> None:
text = src.read_text()
match = re.search(r'(\w+)\[\]\s*=\s*\{([^}]+)\}', text, re.DOTALL)
if not match:
sys.exit(f"No byte array found in {src}")
hex_values = re.findall(r'0x[0-9a-fA-F]{2}', match.group(2))
if not hex_values:
sys.exit(f"No hex bytes found in {src}")
data = bytes(int(h, 16) for h in hex_values)
out.write_bytes(data)
print(f"{match.group(1)}: {len(data)} bytes -> {out}")
if __name__ == "__main__":
src, out = Path(sys.argv[1]), Path(sys.argv[2])
extract(src, out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment