Post

How to Convert .bin Files to C Arrays and Back Using xxd on Linux

Learn how to convert binary (.bin) files to and from C-style arrays using the Linux tool xxd.

In my last post on this topic, I demonstrated how to read and store .bin files using C++, which is particularly useful for integrating binary data into C++ projects, as I did in Waffles Crypt.

However, I wanted a faster and easier way to convert C-style arrays in text files back to .bin files and vice versa that could be used in Linux.

The solution to this was the Linux tool xxd!

Table of Contents

  1. Convert .bin files to C-Style Arrays
  2. Convert C-Style Arrays in .txt files to .bin files
  3. Conclusion

Convert .bin files to C-Style Arrays

With xxd, you can easily convert .bin files to C-style arrays for use in your code:

1
xxd -i file.bin
  • 797c8bfbb70f08bbc20d0f8d8ce11dbb.png

Convert C-Style Arrays in .txt files to .bin files

You can also perform the reverse conversion, using sed and tr to transform text files containing C-style arrays back into binary files:

1
cat input.txt | tr -d ' \n' | sed -n 's/.*{ *\([^}]*\) *}.*/\1/p' | xxd -r -p > output.bin
  • 5ec894df3e90663bc9ca69a519ebb241.png

Conclusion

Hope you learnt something new with this! Happy Hacking! :D

This post is licensed under CC BY 4.0 by the author.