二進位制資料轉陣列及反轉換
阿新 • • 發佈:2019-02-13
有時需要把一些圖片、音訊等二進位制資料轉為陣列形式,嵌入程式碼中。手頭沒有此類工具,就用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')
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()
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 struct02
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
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要做一些修改才能執行。