• 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/env python
# -*- coding:utf-8 -*-

# 将一个文件转换成C语言数组
import sys
html_file = open(sys.argv[1], 'rb') # 打开文件
array_name = sys.argv[1] # 设置默认数组变量名
if len(sys.argv) > 2:
	array_name = sys.argv[2]
print("static const char " + array_name + "[] = {")
while True:
	data = html_file.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, 
};
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐