bin2h.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * bin to header - Part of The peTI-NESulator Project
  3. * bin2h.c: Convert a binary file to a table of uint8_t in a C header file.
  4. *
  5. * Created by Manoel Trapier.
  6. * Copyright 2003-2008 986 Corp. All rights reserved.
  7. *
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. int main(int argc, char *argv[])
  12. {
  13. int i;
  14. char *infile;
  15. FILE *fpin = stdin;
  16. FILE *fpout = stdout;
  17. short c;
  18. infile = "stdin";
  19. if (argc > 1)
  20. {
  21. for(i = 1; argv[i] && argv[i][0] == '-'; i++)
  22. {
  23. if (i < argc)
  24. {
  25. switch(argv[i][1])
  26. {
  27. case 'i':
  28. fpin = fopen(argv[i+1], "rb");
  29. infile = argv[i+1];
  30. if (fpin == NULL)
  31. {
  32. fprintf (stderr, "Error: cannot open in file '%s'\n", argv[i+1]);
  33. exit(-1);
  34. }
  35. i++;
  36. break;
  37. case 'o':
  38. fpout = fopen(argv[i+1], "wb");
  39. if (fpout == NULL)
  40. {
  41. fprintf (stderr, "Error: cannot open out file '%s'\n", argv[i+1]);
  42. exit(-1);
  43. }
  44. i++;
  45. break;
  46. default:
  47. fprintf (stderr, "Error: unknown argument: %s\n", argv[i]);
  48. exit(-1);
  49. }
  50. }
  51. }
  52. }
  53. fprintf(fpout, "/* Generated data file from file '%s' */\n\n\n", infile);
  54. fprintf(fpout, "uint8_t data[] = {\n");
  55. i = 0;
  56. while((c = fgetc(fpin)) >= 0)
  57. {
  58. if (i == 0)
  59. fprintf(fpout, "\t\t0x%02X", (uint8_t)c);
  60. else
  61. fprintf(fpout, ", 0x%02X", (uint8_t)c);
  62. i++;
  63. if (i > 10)
  64. {
  65. fprintf(fpout,", \\\n");
  66. i = 0;
  67. }
  68. }
  69. fprintf(fpout, "\n\t\t};\n");
  70. if (fpin != stdin)
  71. {
  72. fclose(fpin);
  73. }
  74. if (fpout != stdout)
  75. {
  76. fclose(fpout);
  77. }
  78. return 0;
  79. }