/[gxemul]/upstream/20070918/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/20070918/experiments/hex_to_bin.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 45 - (show annotations)
Mon Oct 8 16:23:07 2007 UTC (16 years, 7 months ago) by dpavlin
File MIME type: text/plain
File size: 1486 byte(s)
20070918
1 /*
2 * $Id: hex_to_bin.c,v 1.2 2007/05/11 07:51:56 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 * 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 */
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

  ViewVC Help
Powered by ViewVC 1.1.26