您的位置:首页 > 编程语言 > C语言/C++

将一个文件转换成C语言数组

2015-12-14 19:19 513 查看
hello_word.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>首页</title>
</head>
<body>
hello world!
</body>
</html>


html2hex.py

#!/usr/bin/python
# -*- coding:utf-8 -*-

# 将一个文件转换成C语言数组
import sys
textFile = open(sys.argv[1], 'rb') # 打开文件
arrayName = sys.argv[1] # 设置默认数组变量名
if len(sys.argv) > 2:
arrayName = sys.argv[2]
print("static const char " + arrayName + "[] = {")
while True:
data = textFile.read(16) # 每一次读取16个字符
if not data:
break
str_line = "    " #空出4个空格
for i in data:
str_line += "0x{0:02x}".format(ord(i)) + ", "
print(str_line)
print("};")

# python html2hex.py hello_world.html hello_world


运行命令

python html2hex.py hello_world.html hello_world


运行结果

static const char hello_world[] = {
0x3c, 0x21, 0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45, 0x20, 0x68, 0x74, 0x6d, 0x6c, 0x3e, 0x0a,
0x3c, 0x68, 0x74, 0x6d, 0x6c, 0x3e, 0x0a, 0x3c, 0x68, 0x65, 0x61, 0x64, 0x3e, 0x0a, 0x09, 0x3c,
0x6d, 0x65, 0x74, 0x61, 0x20, 0x68, 0x74, 0x74, 0x70, 0x2d, 0x65, 0x71, 0x75, 0x69, 0x76, 0x3d,
0x22, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79, 0x70, 0x65, 0x22, 0x20, 0x63,
0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x3d, 0x22, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x68, 0x74, 0x6d,
0x6c, 0x3b, 0x20, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x75, 0x74, 0x66, 0x2d, 0x38,
0x22, 0x20, 0x2f, 0x3e, 0x0a, 0x09, 0x3c, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x3e, 0xe9, 0xa6, 0x96,
0xe9, 0xa1, 0xb5, 0x3c, 0x2f, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x3e, 0x0a, 0x3c, 0x2f, 0x68, 0x65,
0x61, 0x64, 0x3e, 0x0a, 0x3c, 0x62, 0x6f, 0x64, 0x79, 0x3e, 0x0a, 0x09, 0x68, 0x65, 0x6c, 0x6c,
0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21, 0x0a, 0x3c, 0x2f, 0x62, 0x6f, 0x64, 0x79, 0x3e,
0x0a, 0x3c, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x3e,
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  html c语言 python