二进制数据转数组及反转换

来源:互联网 发布:java什么时候用返回值 编辑:程序博客网 时间:2024/04/28 20:15
有时需要把一些图片、音频等二进制数据转为数组形式,嵌入代码中。手头没有此类工具,就用python写了一个简单的转换:
01 fileIn = 'demo.bmp'
02 fileOut = 'hex.txt'
03 
04
 inp = open(fileIn,'rb')
05 outp = open(fileOut,'w')
06 i = 0
07 for c in inp.read():
08     outp.write('%#04x,'%(c))
09     i += 1
10     if i >= 16:
11         outp.write('\n')
12         i = 0
13 inp.close()
14 outp.close()
15 print('ok')

转换完把hex.txt中数据写入代码里的数组中。

如果代码是以前写的,往往看着数组不知道是什么图片,就又写了个反转换,将其转为二进制文件。

01 import struct
02 
03
 fileIn = 'hex.txt'
04 fileOut = 'x.bmp'
05 
06 inp = open(fileIn,'r')
07 outp = open(fileOut,'wb')
08 i = 0
09 for mLine in inp.readlines():
10     mList = mLine.strip().split(',')
11     for xc in mList:
12         xc = xc.strip()
13         if xc != '':
14             bc = struct.pack('B',int(xc,16))
15             outp.write(bc)
16 inp.close()
17 outp.close()

以上代码都是在Python3上运行通过的,Python2要做一些修改才能运行。

原创粉丝点击