hex2hex.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. #include <stdio.h>
  7. #include <string.h>
  8. #include <stdlib.h>
  9. #define ABANDON(why) { fprintf(stderr, "%s\n", why); exit(1); }
  10. #define MAX_SIZE (256*1024)
  11. unsigned char buf[MAX_SIZE];
  12. static int loadhex(FILE *inf, unsigned char *buf)
  13. {
  14. int l=0, c, i;
  15. while ((c=getc(inf))!=EOF)
  16. {
  17. if (c == ':') /* Sync with beginning of line */
  18. {
  19. int n, check;
  20. unsigned char sum;
  21. int addr;
  22. int linetype;
  23. if (fscanf(inf, "%02x", &n) != 1)
  24. ABANDON("File format error");
  25. sum = n;
  26. if (fscanf(inf, "%04x", &addr) != 1)
  27. ABANDON("File format error");
  28. sum += addr/256;
  29. sum += addr%256;
  30. if (fscanf(inf, "%02x", &linetype) != 1)
  31. ABANDON("File format error");
  32. sum += linetype;
  33. if (linetype != 0)
  34. continue;
  35. for (i=0;i<n;i++)
  36. {
  37. if (fscanf(inf, "%02x", &c) != 1)
  38. ABANDON("File format error");
  39. if (addr >= MAX_SIZE)
  40. ABANDON("File too large");
  41. buf[addr++] = c;
  42. if (addr > l)
  43. l = addr;
  44. sum += c;
  45. }
  46. if (fscanf(inf, "%02x", &check) != 1)
  47. ABANDON("File format error");
  48. sum = ~sum + 1;
  49. if (check != sum)
  50. ABANDON("Line checksum error");
  51. }
  52. }
  53. return l;
  54. }
  55. int main( int argc, const char * argv [] )
  56. {
  57. const char * varline;
  58. int i,l;
  59. int id=0;
  60. if(argv[1] && strcmp(argv[1], "-i")==0)
  61. {
  62. argv++;
  63. argc--;
  64. id=1;
  65. }
  66. if(argv[1]==NULL)
  67. {
  68. fprintf(stderr,"hex2hex: [-i] filename\n");
  69. exit(1);
  70. }
  71. varline = argv[1];
  72. l = loadhex(stdin, buf);
  73. printf("/*\n *\t Computer generated file. Do not edit.\n */\n");
  74. printf("static int %s_len = %d;\n", varline, l);
  75. printf("static unsigned char %s[] %s = {\n", varline, id?"__initdata":"");
  76. for (i=0;i<l;i++)
  77. {
  78. if (i) printf(",");
  79. if (i && !(i % 16)) printf("\n");
  80. printf("0x%02x", buf[i]);
  81. }
  82. printf("\n};\n\n");
  83. return 0;
  84. }