When working with embedded systems, firmware development, or simply embedding static data into a C or C++ program (like HTML pages or images), you might find yourself needing to convert a file into a C-compatible byte array. This enables you to compile the file's contents directly into the source code - ideal for systems with no filesystem or where external assets must be bundled directly into the binary. This tutorial demonstrates how to generate C-compatible byte array from a file on Linux.
The xxd
command line tool, commonly used for creating hex dumps, includes a very handy option -i
. This option outputs content as a C-style include, ready to paste into the C source code or header file.
Create a sample file for testing:
printf 'Hello world' > test.txt
Generate the C byte array using the command:
xxd -i test.txt
In the terminal, you will see the output:
unsigned char test_txt[] = {
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64
};
unsigned int test_txt_len = 11;
We can save the output directly to a header file as follows:
xxd -i test.txt > test.h
You can now include test.h
in the C or C++ project and use test_txt
and test_txt_len
as needed.
Notes:
- The variable names are derived from the filename. The
test.txt
becomestest_txt
automatically. - This method works with any file type - text, binary, image, etc.
- The generated array is declared as
unsigned char
, making it safe for binary data.
Leave a Comment
Cancel reply