Skip to content

Commit bc08f24

Browse files
committed
[util] Script to convert binary to C arrays
Signed-off-by: Chris Frantz <cfrantz@google.com>
1 parent 8a03b8a commit bc08f24

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

util/sh/scripts/bin2c.sh

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#!/bin/bash
2+
# Copyright lowRISC contributors (OpenTitan project).
3+
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
4+
# SPDX-License-Identifier: Apache-2.0
5+
6+
function usage() {
7+
echo "Convert a binary file to a C array."
8+
echo
9+
echo "$1 [--input FILE] [--output FILE] [--name C_IDENT]"
10+
echo
11+
echo " -i|--input FILE: Input file to convert to C"
12+
echo " -o|--output FILE: Output file name. Defaults to input name with .h appended"
13+
echo " -n|--name C_IDENT: Name of the array."
14+
echo " -?|-h|--help: This message."
15+
echo
16+
}
17+
18+
DIR="$(dirname "$0")"
19+
20+
FILE=""
21+
OUTPUT=""
22+
NAME=""
23+
24+
while [[ $# -gt 0 ]]; do
25+
case "$1" in
26+
-i|--input)
27+
shift
28+
FILE="$1"
29+
shift
30+
;;
31+
-o|--output)
32+
shift
33+
OUTPUT="$1"
34+
shift
35+
;;
36+
-n|--name)
37+
shift
38+
NAME="$1"
39+
shift
40+
;;
41+
-\?|-h|--help)
42+
usage $0
43+
exit 1
44+
;;
45+
*)
46+
echo "Unknown argument: $1"
47+
exit 1
48+
;;
49+
esac
50+
done
51+
52+
if [[ -z ${OUTPUT} ]]; then
53+
OUTPUT="${FILE}.h"
54+
fi
55+
if [[ -z ${NAME} ]]; then
56+
base=$(basename ${FILE})
57+
NAME=$(echo ${base} | sed -e "s/[^A-Za-z0-9_]/_/g")
58+
fi
59+
60+
echo -n "" > ${OUTPUT}
61+
echo "// Copyright lowRISC contributors (OpenTitan project)." >> ${OUTPUT}
62+
echo "// Licensed under the Apache License, Version 2.0, see LICENSE for details." >> ${OUTPUT}
63+
echo "// SPDX-License-Identifier: Apache-2.0" >> ${OUTPUT}
64+
echo "" >> ${OUTPUT}
65+
echo "// clang-format off" >> ${OUTPUT}
66+
echo "const unsigned char ${NAME}[] = {" >> ${OUTPUT}
67+
hexdump -vf "${DIR}/c.hexdump" ${FILE} | sed -e "s/0x ,/ /g" >> ${OUTPUT}
68+
echo "};" >> ${OUTPUT}
69+
echo "// clang-format on" >> ${OUTPUT}

util/sh/scripts/c.hexdump

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
16/1 "0x%02x,"
2+
" // %08_ax " "%_p"
3+
"\n"

0 commit comments

Comments
 (0)