1 /*
2  * hex2hex reads stdin in Intel HEX format and produces an
3  * (unsigned char) array which contains the bytes and writes it
4  * to stdout using C syntax
5  */
6 
7 #include <stdio.h>
8 #include <string.h>
9 #include <stdlib.h>
10 
11 #define ABANDON(why) { fprintf(stderr, "%s\n", why); exit(1); }
12 #define MAX_SIZE (256*1024)
13 unsigned char buf[MAX_SIZE];
14 
loadhex(FILE * inf,unsigned char * buf)15 int loadhex(FILE *inf, unsigned char *buf)
16 {
17 	int l=0, c, i;
18 
19 	while ((c=getc(inf))!=EOF)
20 	{
21 		if (c == ':')	/* Sync with beginning of line */
22 		{
23 			int n, check;
24 			unsigned char sum;
25 			int addr;
26 			int linetype;
27 
28 			if (fscanf(inf, "%02x", &n) != 1)
29 			   ABANDON("File format error");
30 			sum = n;
31 
32 			if (fscanf(inf, "%04x", &addr) != 1)
33 			   ABANDON("File format error");
34 			sum += addr/256;
35 			sum += addr%256;
36 
37 			if (fscanf(inf, "%02x", &linetype) != 1)
38 			   ABANDON("File format error");
39 			sum += linetype;
40 
41 			if (linetype != 0)
42 			   continue;
43 
44 			for (i=0;i<n;i++)
45 			{
46 				if (fscanf(inf, "%02x", &c) != 1)
47 			   	   ABANDON("File format error");
48 				if (addr >= MAX_SIZE)
49 				   ABANDON("File too large");
50 				buf[addr++] = c;
51 				if (addr > l)
52 				   l = addr;
53 				sum += c;
54 			}
55 
56 			if (fscanf(inf, "%02x", &check) != 1)
57 			   ABANDON("File format error");
58 
59 			sum = ~sum + 1;
60 			if (check != sum)
61 			   ABANDON("Line checksum error");
62 		}
63 	}
64 
65 	return l;
66 }
67 
main(int argc,const char * argv[])68 int main( int argc, const char * argv [] )
69 {
70 	const char * varline;
71 	int i,l;
72 	int id=0;
73 
74 	if(argv[1] && strcmp(argv[1], "-i")==0)
75 	{
76 		argv++;
77 		argc--;
78 		id=1;
79 	}
80 	if(argv[1]==NULL)
81 	{
82 		fprintf(stderr,"hex2hex: [-i] filename\n");
83 		exit(1);
84 	}
85 	varline = argv[1];
86 	l = loadhex(stdin, buf);
87 
88 	printf("/*\n *\t Computer generated file. Do not edit.\n */\n");
89         printf("static int %s_len = %d;\n", varline, l);
90 	printf("static unsigned char %s[] %s = {\n", varline, id?"__initdata":"");
91 
92 	for (i=0;i<l;i++)
93 	{
94 		if (i) printf(",");
95 		if (i && !(i % 16)) printf("\n");
96 		printf("0x%02x", buf[i]);
97 	}
98 
99 	printf("\n};\n\n");
100 	return 0;
101 }
102