1 |
dpavlin |
24 |
/* |
2 |
dpavlin |
42 |
* $Id: hex_to_bin.c,v 1.2 2007/05/11 07:51:56 debug Exp $ |
3 |
dpavlin |
24 |
* |
4 |
|
|
* Quick hack to convert .hex files (such as the AVR Hello World program at |
5 |
|
|
* http://www.tfs.net/~petek/atmel/hiworld/hiworld.hex) into raw binaries. |
6 |
|
|
* |
7 |
|
|
* E.g. hex_to_bin hiworld.hex hiworld.bin |
8 |
|
|
* |
9 |
|
|
* and then: gxemul -E bareavr ..... 0:hiworld.bin |
10 |
dpavlin |
42 |
* |
11 |
|
|
* Note: The experimental AVR emulation was removed from GXemul at 20070511. |
12 |
|
|
* Use versions prior to this versions if you want to play with AVR |
13 |
|
|
* emulation. |
14 |
dpavlin |
24 |
*/ |
15 |
|
|
|
16 |
|
|
#include <stdio.h> |
17 |
|
|
|
18 |
|
|
|
19 |
|
|
int fromhex(char *p) |
20 |
|
|
{ |
21 |
|
|
char c1 = p[0], c2 = p[1]; |
22 |
|
|
if (c1 >= '0' && c1 <= '9') |
23 |
|
|
c1 -= '0'; |
24 |
|
|
else if (c1 >= 'A' && c1 <= 'F') |
25 |
|
|
c1 = c1 - 'A' + 10; |
26 |
|
|
if (c2 >= '0' && c2 <= '9') |
27 |
|
|
c2 -= '0'; |
28 |
|
|
else if (c2 >= 'A' && c2 <= 'F') |
29 |
|
|
c2 = c2 - 'A' + 10; |
30 |
|
|
return c1 * 16 + c2; |
31 |
|
|
} |
32 |
|
|
|
33 |
|
|
|
34 |
|
|
int hex_to_bin(char *fname, char *outname) |
35 |
|
|
{ |
36 |
|
|
FILE *f = fopen(fname, "r"); |
37 |
|
|
FILE *fout = fopen(outname, "w"); |
38 |
|
|
|
39 |
|
|
while (!feof(f)) { |
40 |
|
|
char s[80]; |
41 |
|
|
int nbytes, i, addr; |
42 |
|
|
|
43 |
|
|
s[0] = '\0'; |
44 |
|
|
fgets(s, sizeof(s), f); |
45 |
|
|
if (s[0] == 0) |
46 |
|
|
break; |
47 |
|
|
if (s[0] != ':') |
48 |
|
|
continue; |
49 |
|
|
nbytes = fromhex(s+1); |
50 |
|
|
addr = fromhex(s+3) * 256 + fromhex(s+5); |
51 |
|
|
fseek(fout, addr, SEEK_SET); |
52 |
|
|
for (i=0; i<nbytes; i++) { |
53 |
|
|
unsigned char b = fromhex(s+9+i*2); |
54 |
|
|
fwrite(&b, 1, 1, fout); |
55 |
|
|
} |
56 |
|
|
} |
57 |
|
|
|
58 |
|
|
fclose(fout); |
59 |
|
|
fclose(f); |
60 |
|
|
return 0; |
61 |
|
|
} |
62 |
|
|
|
63 |
|
|
|
64 |
|
|
int main(int argc, char *argv[]) |
65 |
|
|
{ |
66 |
|
|
if (argc < 3) { |
67 |
|
|
fprintf(stderr, "usage: %s file.hex output.bin\n", argv[0]); |
68 |
|
|
exit(1); |
69 |
|
|
} |
70 |
|
|
|
71 |
|
|
return hex_to_bin(argv[1], argv[2]); |
72 |
|
|
} |
73 |
|
|
|