Skip to content

Instantly share code, notes, and snippets.

@RandyGaul
Created September 25, 2022 20:17
Show Gist options
  • Save RandyGaul/30f16fd185e3a5ef0a4501f30d57f734 to your computer and use it in GitHub Desktop.
Save RandyGaul/30f16fd185e3a5ef0a4501f30d57f734 to your computer and use it in GitHub Desktop.
Create an array of binary data to embed files into your program directly
// Embedded some small file here.
int g_some_file_sz = 64;
unsigned char g_some_file_data[64] = {
0x10,0xaa,0x98,0xe0,0x10,0x5a,0x3e,0x63,0xe5,0xdf,0xa4,0xb5,0x5d,0xf3,0x3c,0x0a,
0x31,0x5d,0x6e,0x58,0x1e,0xb8,0x5b,0xa4,0x4e,0xa3,0xf8,0xe7,0x55,0x53,0xaf,0x7a,
0x4a,0xc5,0x56,0x47,0x30,0xbf,0xdc,0x22,0xc7,0x67,0x3b,0x23,0xc5,0x00,0x21,0x7e,
0x19,0x3e,0xa4,0xed,0xbc,0x0f,0x87,0x98,0x80,0xac,0x89,0x82,0x30,0xe9,0x95,0x6c
};
// Creates an array like the one above.
// Call it like: print_embedded_symbol("some_file", data, size);
void print_embedded_symbol(const char* sym, void* data, int sz)
{
printf("// Embedded %s\n", sym);
printf("int %s_sz = %d;\n", sym, sz);
printf("unsigned char %s_data[%d] = {\n", sym, sz);
const unsigned char* buf = (const unsigned char*)data;
for (int i = 0; i < sz; ++i) {
printf(
i % 16 == 0 ? "\t0x%02x%s" : "0x%02x%s",
buf[i],
i == sz - 1 ? "" : (i + 1) % 16 == 0 ? ",\n" : ","
);
}
printf("\n};\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment