Skip to content

Instantly share code, notes, and snippets.

@gnat
Last active December 4, 2025 13:57
Show Gist options
  • Select an option

  • Save gnat/6b2d315a927089132367dc9705433b9e to your computer and use it in GitHub Desktop.

Select an option

Save gnat/6b2d315a927089132367dc9705433b9e to your computer and use it in GitHub Desktop.
The brilliant embeddable binary feature of C23 #embed

It's equivalent to #include but for binary files. Lets you embed any binary file similar to C23 #embed https://thephd.dev/implementing-embed-c-and-c++

Originally from https://github.com/Smattr/rumur/blob/7916652b93d1768308a3c1a73bf0a96e62369fb8/misc/xxd.py

#!/usr/bin/env python3
import argparse
import re
import sys

def main(args):
	parser = argparse.ArgumentParser(description='convert file contents to a C++ string')
	parser.add_argument('input', type=argparse.FileType('rb'), help='input file')
	parser.add_argument('output', type=argparse.FileType('wt'), help='output file')
	options = parser.parse_args(args[1:])

	array = re.sub(r'[^\w\d]', '_', options.input.name)
	size = '{}_len'.format(array)

	options.output.write('#include <cstddef>\n' '\n' 'extern const unsigned char {}[] = {{'.format(array))

	index = 0
	while True:
		c = options.input.read(1)
		if c == b'':
			break
		if index % 12 == 0:
			options.output.write('\n ')
		options.output.write(' 0x{:02x},'.format(int.from_bytes(c, byteorder='little')))
		index += 1

	options.output.write('\n' '}};\n' 'extern const size_t {} = sizeof({}) / sizeof({}[0]);\n' .format(size, array, array))

	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