* Added a simple Intel IHX to ROM image converter. Will be removed when
[fw/sdcc] / support / makebin / makebin.c
1 /** @name makebin - turn a .ihx file into a binary image.
2  */
3 #include <stdio.h>
4 #include <unistd.h>
5 #include <stdlib.h>
6
7 typedef unsigned char BYTE;
8
9 #define FILL_BYTE 0xFF
10
11 int getnibble(char **p)
12 {
13   int ret = *((*p)++) - '0';
14   if (ret > 9) {
15     ret -= 'A' - '9' - 1;
16   }
17   return ret;
18 }
19
20 int getbyte(char **p)
21 {
22   return (getnibble(p) << 4) | getnibble(p);
23 }
24
25 int main(int argc, char **argv)
26 {
27     int opt;
28     int size = 32768;
29     BYTE *rom;
30     char line[256];
31     char *p;
32
33     while ((opt = getopt(argc, argv, "s:h"))!=-1) {
34         switch (opt) {
35         case 's':
36             size = atoi(optarg);
37             break;
38         case 'h':
39             printf("makebin: convert a Intel IHX file to binary.\n"
40                    "Usage: %s [-s romsize] [-h]\n", argv[0]);
41             return 0;
42         }
43     }
44     rom = malloc(size);
45     if (rom == NULL) {
46         fprintf(stderr, "error: couldn't allocate room for the image.\n");
47         return -1;
48     }
49     memset(rom, FILL_BYTE, size);
50     while (fgets(line, 256, stdin) != NULL) {
51         int nbytes;
52         int addr;
53
54         if (*line != ':') {
55             fprintf(stderr, "error: invalid IHX line.\n");
56             return -2;
57         }
58         p = line+1;
59         nbytes = getbyte(&p);
60         addr = getbyte(&p)<<8 | getbyte(&p);
61         getbyte(&p);
62
63         while (nbytes--) {
64             if (addr < size)
65                 rom[addr++] = getbyte(&p);
66         }
67     }
68     fwrite(rom, 1, size, stdout);
69     return 0;
70 }