make-c-array

This script prints binary data as an C array. This is useful for inserting binary blobs into source code. The script takes binary data in via stdin, and prints it out via stdout, so that it can work in a pipe.

#!/bin/bash

FILE=$1
NAME=$2

echo "const unsigned char $NAME[] = {"
od -v -w8 -tx1 $FILE | cut -c8- | \
	sed \
		-e"s/ / 0x/g" \
		-e"s/ 0x/, 0x/g" \
		-e"s/^, \(.*\)/    \1/" \
		-e"$ d" |
	sed -e"$ !s/.*/&,/"
echo "};"

Usage

File Input

To print a file:

 $ make-c-array in.bin Test > out.c

Where in.bin is the binary input file, Test is the name of the array, and out is the name of the C file to output to:

const unsigned char Test[] = {
    0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x03, 0xff, 0xc4, 0x00, 0x14,
    0x00, 0x00, 0xff, 0xda, 0x00, 0x08, 0x01, 0x01,
    0x00, 0x00, 0x3f, 0x00, 0x37, 0xff, 0xd9
};
Pipe Input

make-c-array can also take an input from stdin:

 $ echo "Binary Test Data" | make-c-array - Hello > out.c

Result:

const unsigned char Test[] = {
    0x42, 0x69, 0x6e, 0x61, 0x72, 0x79, 0x20, 0x54,
    0x65, 0x73, 0x74, 0x20, 0x44, 0x61, 0x74, 0x61,
    0x0a
};
make-c-array.txt ยท Last modified: 2017/12/06 11:18 (external edit)