File: bin2c.py

package info (click to toggle)
wxpython4.0 4.2.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 232,540 kB
  • sloc: cpp: 958,937; python: 233,059; ansic: 150,441; makefile: 51,662; sh: 8,687; perl: 1,563; javascript: 584; php: 326; xml: 200
file content (47 lines) | stat: -rwxr-xr-x 1,287 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python
#
# This is a slightly generalized version of png2c.py and is based on it.

import sys
import os
import os.path
import re
import array

if len(sys.argv) < 2:
        print("""Usage: bin2c binary_file...

Output input files data as C arrays to standard output.""")
        sys.exit(1)

r = re.compile("^([a-zA-Z._][a-zA-Z._0-9]*)[.]([a-zA-Z_0-9]+)$")
for path in sys.argv[1:]:
        filename = os.path.basename(path).replace('-','_')
        m = r.match(filename)

        # Allow only filenames that make sense as C variable names
        if not(m):
                print("Skipped file (unsuitable filename): " + filename)
                continue

        # Read file as character array
        bytes = array.array('B', open(path, "rb").read())
        count = len(bytes)

        # Create the C header
        text = "/* %s - %d bytes */\n" \
               "static const unsigned char %s_%s_data[] = {\n" % (
                    filename, count, m.group(1), m.group(2))

        i = 0
        for byte in bytes:
                if i % 16 == 0:
                        text += "\n   "
                i += 1
                text += " 0x%02x" % byte
                if i != count:
                        text += ","

        text += "\n};"

        print(text)