diff --git a/bin2c.c b/bin2c.c index 8cecc99..5994006 100644 --- a/bin2c.c +++ b/bin2c.c @@ -14,6 +14,8 @@ #include #include +#define COLS 16 + #ifdef USE_BZ2 #include #endif @@ -21,9 +23,12 @@ int main(int argc, char *argv[]) { - char *buf; - char *ident; - unsigned int i, file_size, need_comma; + unsigned char *buf; + char array_name[80]; + unsigned int i, file_size, file_count, need_comma; + int incr = 1; + int arg = 1; + const char* filename; FILE *f_input, *f_output; @@ -33,14 +38,19 @@ main(int argc, char *argv[]) #endif if (argc < 4) { - fprintf(stderr, "Usage: %s binary_file output_file array_name\n", + fprintf(stderr, "Usage: %s [-w] binary_file output_file [array_name]\n", argv[0]); return -1; } - f_input = fopen(argv[1], "rb"); + if (strcmp(argv[arg], "-w") == 0) { + ++arg; incr = 2; + } + + filename = argv[arg++]; + f_input = fopen(filename, "rb"); if (f_input == NULL) { - fprintf(stderr, "%s: can't open %s for reading\n", argv[0], argv[1]); + fprintf(stderr, "%s: can't open %s for reading\n", argv[0], filename); return -1; } @@ -49,7 +59,7 @@ main(int argc, char *argv[]) file_size = ftell(f_input); fseek(f_input, 0, SEEK_SET); - buf = (char *) malloc(file_size); + buf = (unsigned char *) malloc(file_size); assert(buf); fread(buf, file_size, 1, f_input); @@ -79,32 +89,52 @@ main(int argc, char *argv[]) buf = bz2_buf; #endif - f_output = fopen(argv[2], "w"); + filename = argv[arg++]; + f_output = fopen(filename, "w"); if (f_output == NULL) { - fprintf(stderr, "%s: can't open %s for writing\n", argv[0], argv[1]); + fprintf(stderr, "%s: can't open %s for writing\n", argv[0], filename); return -1; } - ident = argv[3]; + // Check if array_name passed on command line + if (arg < argc) { + strcpy(array_name, argv[arg]); + } else { + char ch; + strcpy(array_name, filename); + // Replace non-alphanumeric chars with underscore + for (i = 0; (ch = array_name[i]) != '\0'; ++i) { + if (!isalpha(ch) && !isdigit(ch)) { + array_name[i] = '_'; + } + } + + } need_comma = 0; + + file_count = file_size / incr; - fprintf(f_output, "const char %s[%i] = {", ident, file_size); - for (i = 0; i < file_size; ++i) { + fprintf(f_output, "const unsigned short %s[%i] = {", array_name, file_count); + for (i = 0; i < file_size; i += incr) { if (need_comma) fprintf(f_output, ", "); else need_comma = 1; - if ((i % 11) == 0) + if ((i % COLS) == 0) fprintf(f_output, "\n\t"); - fprintf(f_output, "0x%.2x", buf[i] & 0xff); + if (incr > 1) { + fprintf(f_output, "0x%04x", buf[i] | (buf[i + 1] << 8)); + } else { + fprintf(f_output, "0x%02x", buf[i]); + } } fprintf(f_output, "\n};\n\n"); - fprintf(f_output, "const int %s_length = %i;\n", ident, file_size); + fprintf(f_output, "const int %s_length = %i;\n", array_name, file_count); #ifdef USE_BZ2 - fprintf(f_output, "const int %s_length_uncompressed = %i;\n", ident, + fprintf(f_output, "const int %s_length_uncompressed = %i;\n", array_name, uncompressed_size); #endif