需求
將二進(jìn)制數(shù)據(jù)的bin文件轉(zhuǎn)換成C語(yǔ)言數(shù)組的形式并保存為 .c 源文件
"""
將二進(jìn)制數(shù)據(jù)的bin文件轉(zhuǎn)換成C語(yǔ)言數(shù)組的形式并保存為 .c 源文件
"""
import sys
def main():
if not sys.argv[1]:
print("bin file error")
return
binListData = []
# 讀取二進(jìn)制文件存放到list列表中
file = open(sys.argv[1], 'rb')
file.seek(0, 0)
while True:
binByte = file.read(1)
if len(binByte) == 0:
break
else:
binListData.append("0x%.2x" % ord(binByte))
file.close()
# 將列表中的數(shù)據(jù)寫(xiě)入到 .c 源文件中
fileOutput = open("bin2c.c", 'w')
fileOutput.write("unsigned long hexLength = {};\n".format(len(binListData)))
fileOutput.write("unsigned char hexData[] = \n")
fileOutput.write("{\n")
for i in range(len(binListData)):
if (i != 0) and (i % 16 == 0):
fileOutput.write("\n")
fileOutput.write(binListData[i] + ",")
elif (i + 1) == len(binListData):
fileOutput.write(binListData[i])
else:
fileOutput.write(binListData[i] + ",")
fileOutput.write("\n};")
fileOutput.close()
print("bin file to C array file success!!!")
if __name__ == '__main__':
main()
運(yùn)行:
編輯一個(gè)bat批處理腳本文件朱巨,如下所示虽另,雙擊該bat文件即可
python bin2c.py test.bin
pause