1. 程式人生 > >把unicode編碼的十六進位制字串轉換為漢字(Python2.7)

把unicode編碼的十六進位制字串轉換為漢字(Python2.7)

#小端位元組序轉為大端位元組序
def little2big_endian(hex_string):
	big_endian_str = '' #定義一個空字串
	for i in range(len(hex_string)/4):#因為Unicode是4個字元表示一個漢字,每四個一組
		little_endian_char = hex_string[i*4: i*4+4] #取的是四位連續的數字
		big_endian_char = little_endian_char[2:4] + little_endian_char[0:2] #逆位元組序
		big_endian_str = big_endian_str + big_endian_char
	return big_endian_str

#十六進位制數字(大端序)轉換成漢字(unicode編碼)
def HextoHanzi(hex_string):
	unicode_Hanzi = '' #定義一個空字串
	for i in range(len(hex_string)/4): #因為Unicode是4個字元表示一個漢字,每四個一組
		Hex_char = hex_string[i*4: i*4+4]
		unicode_char = "\\u" + Hex_char
		unicode_Hanzi = unicode_Hanzi + unicode_char
	return unicode_Hanzi.decode('unicode_escape')

hex_string = '1162B07328572857005F1A4F62546153A16C265EAB8EB98F'
big_endian_str = little2big_endian(hex_string)
print HextoHanzi(big_endian_str)