]> git.sesse.net Git - nageru/blobdiff - shared/bin2h.cpp
Move bin2h and read_file into shared/, so that Nageru can also use it.
[nageru] / shared / bin2h.cpp
diff --git a/shared/bin2h.cpp b/shared/bin2h.cpp
new file mode 100644 (file)
index 0000000..a396afe
--- /dev/null
@@ -0,0 +1,51 @@
+#include <stdio.h>
+#include <string>
+
+using namespace std;
+
+int main(int argc, char **argv)
+{
+       if (argc != 4) {
+               fprintf(stderr, "Usage: bin2h INFILE BASENAME OUTFILE\n");
+               return 1;
+       }
+
+       string basename = argv[2];
+       for (char &ch : basename) {
+               if (!isalpha(ch) && !isdigit(ch)) {
+                       ch = '_';
+               }
+       }
+
+       FILE *infp = fopen(argv[1], "rb");
+       if (infp == nullptr) {
+               perror(argv[1]);
+               exit(1);
+       }
+
+       FILE *outfp = fopen(argv[3], "w");
+       if (outfp == nullptr) {
+               perror(argv[3]);
+               exit(1);
+       }
+
+       fprintf(outfp, "// Generated by bin2h.cpp from %s. Do not edit by hand.\n", argv[1]);
+       fprintf(outfp, "#include <stddef.h>\n");
+       fprintf(outfp, "unsigned char _binary_%s[] = {", basename.c_str());
+
+       size_t num_bytes = 0;
+       while (!feof(infp)) {
+               if (num_bytes++ % 16 == 0) {
+                       fprintf(outfp, "\n\t");
+               }
+               int ch = getc(infp);
+               if (ch == -1) {
+                       break;
+               }
+               fprintf(outfp, "0x%02x, ", ch);
+       }
+       fprintf(outfp, "\n};\n");
+       fprintf(outfp, "unsigned char *_binary_%s_data = _binary_%s;\n", basename.c_str(), basename.c_str());
+       fprintf(outfp, "size_t _binary_%s_size = sizeof(_binary_%s);\n", basename.c_str(), basename.c_str());
+       return 0;
+}