把汉字转为UTF-8 16进制字符串,并加\x,针对一些编译器不认识汉字使用
#coding: utf-8
import os
import sys
import re
import binascii
reload(sys)
# sys.setdefaultencoding('utf-8')
sys.setdefaultencoding('gbk')
def str_to_hexStr(string):
str_bin = string.encode('utf-8')
return binascii.hexlify(str_bin).decode('utf-8')
def str_to_hex(arg):
text_str = str(arg)
text_str = str_to_hexStr(text_str)
text_str = text_str.upper()
text_str = re.sub(r"(?<=\w)(?=(?:\w\w)+$)", "\\x", text_str)
text_str = "\\x" + text_str
return "%s-->%s" % (arg, text_str)
def file_to_hex(arg):
wf = open("out."+arg, 'w')
for text_str in open (arg, 'r'):
text_str = text_str.replace('\n','')
text_str = str_to_hex(text_str)
print text_str
wf.write(text_str+"\n")
if __name__=="__main__":
# str_to_hex(sys.argv[1])
file_to_hex(sys.argv[1])