Posted By

mwb1100 on 08/07/09


Tagged


Versions (?)

bin2c


 / Published in: C
 

URL: http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c

GPL licensed by Adrian Prantl

  1. /*
  2.  * bin2c: A Program to convert binary data into C source code
  3.  * Copyright 2004 by Adrian Prantl <[email protected]>
  4.  *
  5.  * This program is free software; you can redistribute it and/or modify
  6.  * it under the terms of the GNU General Public License as published by
  7.  * the Free Software Foundation; either version 2 of the License, or
  8.  * (at your option) any later version.
  9.  *
  10.  */
  11.  
  12. #include <stdio.h>
  13. #include <unistd.h>
  14.  
  15. char* self = 0;
  16.  
  17. void usage()
  18. {
  19. printf("Usage:\n%s input_binary_file output_c_file symbol_name\n\n", self);
  20. }
  21.  
  22. void bail_out(const char* s1, const char* s2)
  23. {
  24. fprintf(stderr, "%s: FATAL ERROR:\n%s%s\n", self, s1, s2);
  25. exit(1);
  26. }
  27.  
  28. int main(int argc, char** argv)
  29. {
  30. FILE *fi, *fo;
  31. int c, i;
  32.  
  33. self = argv[0];
  34.  
  35. if (argc != 4) {
  36. usage();
  37. return 1;
  38. }
  39.  
  40. if ((fi = fopen(argv[1], "rb")) == 0)
  41. bail_out("Cannot open input file ", argv[1]);
  42.  
  43. if ((fo = fopen(argv[2], "w")) == 0)
  44. bail_out("Cannot open output file ", argv[2]);
  45.  
  46. if ((c = fgetc(fi)) != EOF) {
  47. fprintf(fo, "extern volatile unsigned char _binary_%s_start[];\n", argv[3]);
  48. fprintf(fo, "volatile unsigned char _binary_%s_start[] = {\n", argv[3]);
  49. fprintf(fo, c<16 ? " 0x%x" : " 0x%x", (unsigned char)c);
  50. }
  51.  
  52. i = 1;
  53. while ((c = fgetc(fi)) != EOF) {
  54. if (i < 12)
  55. fprintf(fo, c<16 ? ", 0x%x" : ", 0x%x", (unsigned char)c);
  56. else {
  57. fprintf(fo, c<16 ? ",\n 0x%x" : ",\n 0x%x", (unsigned char)c);
  58. i = 0;
  59. }
  60. i++;
  61. }
  62. fprintf(fo, " };\n");
  63.  
  64. printf("converted %s\n", argv[1]);
  65.  
  66. return 0;
  67. }

Report this snippet  

You need to login to post a comment.