hex2hex.c 2.0 KB

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