Linux tool: convert binary file to C/C++ source code array



In case you are programming under Linux and have a binary file that want "import" inside your C/C++ code is there an useful linux utility tool called xxd able to make such conversion in a very easy way. This tool is usually installed by default in all major linux distributions.


 The use is very simple, if you have a binary file called, for example, MyFile.bin with length of 100 bytes and wan to convert in a C/C++ source code array you can simply type:

xxd -i MyFile.bin > MyFile.h

The source code array generated inside the header file will have a format like the following:

unsigned char MyFile[] = {
  0xXX, 0xXX, ....., 0xXX
};
unsigned int MyFile_len = 100;

Obviously 0xXX is the hexadecimal content of the binary file. Now you can import the header file just generated and use in your project.

4 Comments:

This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

Love from

June 19, 2016 at 12:24 PM comment-delete

This comment has been removed by the author.

November 10, 2016 at 10:03 AM comment-delete

It depends by the library methods. Using this way you basically have the binary file content (like an audio file as in your example) loaded in memory. Looking into the documentation of the sfml library you mentioned I think you can use the method sf::SoundBuffer::loadFromMemory()

November 10, 2016 at 12:39 PM comment-delete

This comment has been removed by the author.

November 11, 2016 at 9:38 AM comment-delete

Post a Comment