用Python將二進制文件轉化爲數組並以文件形式存儲

最近在學習Python,發現Python語言很是適合文件的批處理操做。本文將介紹一下用Python如何實現將一個二進制bin文件轉化爲一個常量數組的.c文件存儲起來。這爲咱們在一些沒有文件系統不能調用fopen、fread之類的工程中提供了便利,咱們能夠以常量數組的形式去訪問這些常量數據;另外在算法性能優化時,也能夠利用此程序將一些複雜浮點運算提早變成表格,以查表的形式來提升運算效率。固然,轉化爲常量數組可能會比較耗費內存。閒話少說,代碼以下:算法

 1 import os
 2 
 3 def read_data_from_binary_file(filename, list_data):
 4     f = open(filename, 'rb')
 5     f.seek(0, 0)
 6     while True:
 7         t_byte = f.read(1)
 8         if len(t_byte) == 0:
 9             break
10         else:
11             list_data.append("0x%.2X" % ord(t_byte))
12 
13 def write_data_to_text_file(filename, list_data,data_num_per_line):
14     f_output = open(filename, 'w+')
15     f_output.write('#include<sys/type.h> \n')
16     f_output.write('const unsigned char test_img[] = \n')
17     f_output.write('{\n    ')
18     if ((data_num_per_line <= 0) or data_num_per_line > len(list_data)):
19         data_num_per_line = 16
20         print('data_num_per_line out of range,use default value\n')
21     for i in range(0,len(list_data)):
22         if ( (i != 0) and(i % data_num_per_line == 0)):
23             f_output.write('\n    ')
24             f_output.write(list_data[i]+', ')
25         elif (i + 1) == len(list_data):
26             f_output.write(list_data[i])
27         else:
28             f_output.write(list_data[i]+', ')    
29     f_output.write('\n};')
30     f_output.close()
31 
32 list_data = []
33 input_f = raw_input("Please input source bin file_name:")
34 output_f = raw_input("Please input dest C file name:")
35 data_num_per_line = input("Please input a num whitch indicates how many data for one line:")
36 read_data_from_binary_file(input_f, list_data)
37 write_data_to_text_file(output_f, list_data,data_num_per_line )
相關文章
相關標籤/搜索