Search
lxdream.org :: lxdream/test/bin2c.c
lxdream 0.9.1
released Jun 29
Download Now
filename test/bin2c.c
changeset 561:533f6b478071
prev185:6755a04c447f
author nkeynes
date Tue Jan 01 05:08:38 2008 +0000 (12 years ago)
branchlxdream-mmu
permissions -rw-r--r--
last change Enable Id keyword on all source files
file annotate diff log raw
nkeynes@185
     1
/* Converts a binary file into a C integer array (for inclusion in
nkeynes@185
     2
   a source file) 
nkeynes@185
     3
nkeynes@185
     4
   (c)2000 Dan Potter
nkeynes@185
     5
nkeynes@561
     6
   $Id$
nkeynes@185
     7
   Note: Licensed under the new BSD license, see README.KOS  -NK
nkeynes@185
     8
*/
nkeynes@185
     9
nkeynes@185
    10
#include <stdio.h>
nkeynes@185
    11
nkeynes@185
    12
void convert(char *ifn, char *ofn, char *prefix) {
nkeynes@185
    13
	FILE *i, *o;
nkeynes@185
    14
	unsigned char buffer[2048];
nkeynes@185
    15
	int red, left, lc, q;
nkeynes@185
    16
	char buf[BUFSIZ];
nkeynes@185
    17
nkeynes@185
    18
	i = fopen(ifn, "rb");
nkeynes@185
    19
	o = fopen(ofn, "w");
nkeynes@185
    20
	if (!i || !o) {
nkeynes@185
    21
		printf("error: can't open input or output file\n");
nkeynes@185
    22
		return;
nkeynes@185
    23
	}
nkeynes@185
    24
nkeynes@185
    25
	fseek(i, 0, SEEK_END); left = ftell(i); fseek(i, 0, SEEK_SET);
nkeynes@185
    26
	setbuf(o, buf);
nkeynes@185
    27
nkeynes@185
    28
	fprintf(o, "const int %s_size = %d;\n", prefix, left);
nkeynes@185
    29
	fprintf(o, "const unsigned char %s_data[%d] =", prefix, left);
nkeynes@185
    30
	fprintf(o, "{\n\t");
nkeynes@185
    31
nkeynes@185
    32
	lc = 0;
nkeynes@185
    33
	while(left > 0) {
nkeynes@185
    34
		red = fread(buffer, 1, 2048, i);
nkeynes@185
    35
		left -= red;
nkeynes@185
    36
		for (q=0; q<red; q++) {
nkeynes@185
    37
			fprintf(o, "0x%02x, ", buffer[q]);
nkeynes@185
    38
			if ((++lc) >= 8) {
nkeynes@185
    39
				lc = 0;
nkeynes@185
    40
				fprintf(o, "\n\t");
nkeynes@185
    41
			}
nkeynes@185
    42
		}
nkeynes@185
    43
	}
nkeynes@185
    44
nkeynes@185
    45
	fprintf(o, "\n};\n");
nkeynes@185
    46
	fclose(i); fclose(o);
nkeynes@185
    47
}
nkeynes@185
    48
nkeynes@185
    49
int main(int argc, char **argv) {
nkeynes@185
    50
nkeynes@185
    51
	char *prefix;
nkeynes@185
    52
nkeynes@185
    53
	argc--;
nkeynes@185
    54
	if (argc != 2 && argc != 3) {
nkeynes@185
    55
		printf("usage: bin2c <input> <output> [prefix]\n");
nkeynes@185
    56
		return 0;
nkeynes@185
    57
	}
nkeynes@185
    58
nkeynes@185
    59
	prefix = (argc == 3) ? argv[3] : "file";
nkeynes@185
    60
	convert(argv[1], argv[2], prefix);
nkeynes@185
    61
	return 0;
nkeynes@185
    62
}
nkeynes@185
    63
.