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.

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. 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()

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. if i have unsigned char MyFile[] = {
    0xXX, 0xXX, ....., 0xXX
    }; how do i convert it back to binary?

    ReplyDelete
    Replies
    1. That's what I'd like to know too. I already have the unsigned char array but want the original binary file back. Using some online tool to do so then download the file it creates from the array.

      Delete

Post a Comment

Popular posts from this blog

Access GPIO from Linux user space

Android: adb push and read-only file system error

Tree in SQL database: The Nested Set Model