/[gxemul]/upstream/0.4.3/experiments/hex_to_bin.c
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Contents of /upstream/0.4.3/experiments/hex_to_bin.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 33 - (show annotations)
Mon Oct 8 16:21:06 2007 UTC (16 years, 6 months ago) by dpavlin
File MIME type: text/plain
File size: 1309 byte(s)
0.4.3
1 /*
2 * $Id: hex_to_bin.c,v 1.1 2006/02/26 11:22:23 debug Exp $
3 *
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 */
11
12 #include <stdio.h>
13
14
15 int fromhex(char *p)
16 {
17 char c1 = p[0], c2 = p[1];
18 if (c1 >= '0' && c1 <= '9')
19 c1 -= '0';
20 else if (c1 >= 'A' && c1 <= 'F')
21 c1 = c1 - 'A' + 10;
22 if (c2 >= '0' && c2 <= '9')
23 c2 -= '0';
24 else if (c2 >= 'A' && c2 <= 'F')
25 c2 = c2 - 'A' + 10;
26 return c1 * 16 + c2;
27 }
28
29
30 int hex_to_bin(char *fname, char *outname)
31 {
32 FILE *f = fopen(fname, "r");
33 FILE *fout = fopen(outname, "w");
34
35 while (!feof(f)) {
36 char s[80];
37 int nbytes, i, addr;
38
39 s[0] = '\0';
40 fgets(s, sizeof(s), f);
41 if (s[0] == 0)
42 break;
43 if (s[0] != ':')
44 continue;
45 nbytes = fromhex(s+1);
46 addr = fromhex(s+3) * 256 + fromhex(s+5);
47 fseek(fout, addr, SEEK_SET);
48 for (i=0; i<nbytes; i++) {
49 unsigned char b = fromhex(s+9+i*2);
50 fwrite(&b, 1, 1, fout);
51 }
52 }
53
54 fclose(fout);
55 fclose(f);
56 return 0;
57 }
58
59
60 int main(int argc, char *argv[])
61 {
62 if (argc < 3) {
63 fprintf(stderr, "usage: %s file.hex output.bin\n", argv[0]);
64 exit(1);
65 }
66
67 return hex_to_bin(argv[1], argv[2]);
68 }
69

  ViewVC Help
Powered by ViewVC 1.1.26