Skip to content

Instantly share code, notes, and snippets.

@aji
Created February 18, 2012 06:09
Show Gist options
  • Save aji/1857763 to your computer and use it in GitHub Desktop.
Save aji/1857763 to your computer and use it in GitHub Desktop.
rcc -- convert a file to a C array of unsigned integers
#!/bin/bash
# rcc.sh -- convert a file to a C array of uint16_t's
while getopts ":o:h:e:n:v" opt; do
case $opt in
o) output=$OPTARG
;;
h) header=$OPTARG
;;
e) varre=$OPTARG
;;
v) verbose="yes"
;;
\?) echo "Invalid option -$OPTARG; ignored" >&2
;;
:) echo "Option -$OPTARG requires a parameter; ignored" >&2
;;
esac
done
inputs=${@:$OPTIND}
if [ ${#inputs} = "0" ]; then
echo "No input files given." >&2 ; exit 1 ; fi
if [ -z "$output" ]; then
output='resources.c'
if [ -n "$verbose" ]; then
echo "Output defaulting to $output" >&2; fi
fi
if [ -z "$header" ]; then
header=$(echo $output | sed 's/\.[a-zA-Z0-9]*$/.h/')
if [ -n "$verbose" ]; then
echo "Header file defaulting to $header" >&2; fi
fi
headername=$(echo $header \
| sed 's/[^a-zA-Z0-9]/_/g' \
| tr '[:lower:]' '[:upper:]' \
| sed 's/^/__RC_/' \
| sed 's/$/__/')
echo "/* $output - automatically generated by rcc.sh */" > $output
echo '#include <stdint.h>' >> $output
echo >> $output
echo "/* $header - automatically generated by rcc.sh */" > $header
echo "#ifndef $headername" >> $header
echo "#define $headername" >> $header
echo '#include <stdint.h>' >> $header
for input in $inputs; do
if [ ! -e "$input" ]; then
echo "$input does not exist; ignored" >&2
elif [ ! -f "$input" ]; then
echo "$input is not a regular file; ignored" >&2
else
varname=$(echo $input | sed $varre | sed 's/[^a-zA-Z0-9]/_/g')
varsize=$(wc -c $input | awk '{print $1}')
echo "" >> $output
echo "uint8_t $varname[$varsize] = {" >> $output
od -v -t u1 $input \
| awk '{$1="";print}' \
| sed 's/\([0-9][0-9]*\)/xxx\1/g' \
| sed -e 's/x*\([x0-9]\{3\}\)/\1,/g' \
| sed 's/x/ /g' \
>> $output
echo '};' >> $output
echo "" >> $output
echo "extern uint8_t $varname[$varsize];" >> $header
fi
done
echo "#endif /* $headername */" >> $header
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment