/+junk/bin2cc

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/%2Bjunk/bin2cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3

import sys
from io import StringIO
from io import BufferedReader
import zlib

##################
# bin2cc - embedding compressed data in C files.
# 
# 1) Do what the fuck you want with this code.
# 
##################
# Examlpe:
# Create the C file with the compressed data:
# $ python3 bin2cc.py ../xorg.png > test.c
# 
# Add this to the end of the file:
# 
#int main (int argc, char ** argv) {
#  
#  unsigned char * out_buff = malloc(_xorg_png_real_len);
#  
#  uLongf outlen;
#  
#  uncompress (out_buff, &outlen, _xorg_png, _xorg_png_len);
#  
#  FILE * f = fopen ("../xorg_2.png", "wb");
#  fwrite (out_buff, 1, _xorg_png_real_len, f);
#  fclose (f);
#  return 0;
#}
##################

def main ():
  try:
    file_name = sys.argv[1]
  except IndexError:
    print ("Must provide a file...");
    raise SystemExit
  
  f = open (file_name, "rb")
  
  buff_bytes = f.read ()
  
  compressed_buff = zlib.compress (buff_bytes)
  compressed_buff_len = len (compressed_buff)
  
  out_str = StringIO ()
  
  
  sane_file_name = file_name.replace (".","_").replace("/","_").replace("__","")
  out_str.write ("const unsigned char ")
  out_str.write (sane_file_name)
  out_str.write ("[] = {")
  
  counter = 0
  
  for i in range (0, len (compressed_buff)):
    byte = compressed_buff[i]
    
    out_str.write ("0x%02x," % byte)
    
    if (counter % 10 == 0):
      out_str.write ("\n")
    counter+=1
  
  out_str.write("};")
  
  out_str.write ("\n\nsize_t %s_len = %i;" % (sane_file_name, compressed_buff_len) )
  out_str.write ("\n\nsize_t %s_real_len = %i;" % (sane_file_name, len (buff_bytes)) )
  
  print (out_str.getvalue())

main ()