File: binary2cpp.cpp

package info (click to toggle)
halide 21.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 55,752 kB
  • sloc: cpp: 289,334; ansic: 22,751; python: 7,486; makefile: 4,299; sh: 2,508; java: 1,549; javascript: 282; pascal: 207; xml: 127; asm: 9
file content (65 lines) | stat: -rw-r--r-- 1,734 bytes parent folder | download | duplicates (3)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#ifdef _WIN32
#include <fcntl.h>  // O_BINARY
#include <io.h>     // setmode
#endif

// Embeds a binary blob (from stdin) in a C++ source array of unsigned
// chars. Similar to the xxd utility.

namespace {
int usage() {
    fprintf(stderr, "Usage: binary2cpp identifier [-header]\n");
    return -1;
}
}  // namespace

int main(int argc, const char **argv) {
    const char *target = argv[1];
    if (argc == 3) {
        if (!strcmp(argv[2], "-header")) {
            printf("#ifndef _H_%s_binary2cpp\n", target);
            printf("#define _H_%s_binary2cpp\n", target);
            printf("extern \"C\" {\n");
            printf("extern unsigned char %s[];\n", target);
            printf("extern int %s_length;\n", target);
            printf("}  // extern \"C\"\n");
            printf("#endif  // _H_%s_binary2cpp\n", target);
            return 0;
        } else {
            return usage();
        }
    } else if (argc > 3) {
        return usage();
    }

#ifdef _WIN32
    setmode(fileno(stdin), O_BINARY);  // On windows bad things will happen unless we read stdin in binary mode
#endif
    printf("extern \"C\" {\n");
    printf("unsigned char %s[] = {\n", target);
    int count = 0;
    int line_break = 0;
    while (true) {
        int c = getchar();
        if (c == EOF) {
            break;
        }
        printf("0x%02x, ", c);
        // Not necessary, but makes a bit easier to read
        if (++line_break > 12) {
            printf("\n");
            line_break = 0;
        }
        count++;
    }
    printf("0};\n");
    printf("int %s_length = %d;\n", target, count);
    printf("}  // extern \"C\"\n");
    return 0;
}