bin2h.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 Manoël Trapier.
  6. * Copyright (c) 2002-2019 986-Studio.
  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. {
  60. fprintf(fpout, "\t\t0x%02X", (uint8_t)c);
  61. }
  62. else
  63. {
  64. fprintf(fpout, ", 0x%02X", (uint8_t)c);
  65. }
  66. i++;
  67. if (i > 10)
  68. {
  69. fprintf(fpout, ", \\\n");
  70. i = 0;
  71. }
  72. }
  73. fprintf(fpout, "\n\t\t};\n");
  74. if (fpin != stdin)
  75. {
  76. fclose(fpin);
  77. }
  78. if (fpout != stdout)
  79. {
  80. fclose(fpout);
  81. }
  82. return 0;
  83. }