How to Use bin2c: Convert Binary Files to C Arrays Quickly

How to Use bin2c: Convert Binary Files to C Arrays Quickly

What bin2c does

bin2c converts a binary file (image, font, firmware blob, etc.) into a C source file containing a byte array and a length constant you can include in embedded or desktop C projects.

Typical output

  • A .c file defining:
    • const unsigned char [] = {0x00, 0x01, …};
    • const unsigned int len = ;

Common command-line usage

Assuming a simple bin2c that accepts input and output filenames:

  • Convert file.bin to file.c:

    Code

    bin2c file.bin file.c
  • Specify symbol name (if supported):

    Code

    bin2c -n my_data file.bin file.c

(If your bin2c variant differs, check its help: bin2c –help or bin2c -h.)

Integration tips

  • Include the generated header/source:
    • Either include the generated .c in your build and declare extern in a header, or
    • Generate a .h with extern const unsigned char my_data[]; and extern const unsigned int my_data_len; and include that.
  • Use const to place data in flash/RO memory on embedded targets.
  • Align arrays or use linker scripts if hardware requires specific placement.

Size & performance

  • Large binaries produce large object files; consider:
    • Compressing data (zlib/LZ4) and decompressing at runtime.
    • Storing in read-only filesystem or external flash instead of embedding.
  • Use uint8_t and sizet for portability:

    Code

    const uint8_t my_data[] = { … }; const size_t my_data_len = sizeof(mydata);

Build automation

  • Add a rule to your Makefile or CMake to regenerate sources when the binary changes.
    • Makefile example:

      Code

      %.c: %.bin bin2c \(< \)@
    • CMake: use add_custom_command to generate .c and add to sources.

Safety and portability

  • Watch symbol name collisions; choose unique names.
  • Ensure generated files use correct endianness expectations (bin2c preserves byte order).
  • Check compiler limits for very large static arrays.

Quick checklist

  • Run bin2c on the binary
  • Verify generated symbol names
  • Add generated .c/.h to build system
  • Use const and appropriate integer types
  • Consider compression for very large blobs

If you want, I can generate an example command and Makefile rule tailored to your bin2c implementation and target platform — tell me the tool flags or target (embedded Linux, bare-metal, etc.).

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *