unicode編碼范圍
00000000-0000007F的字符,用單個字節來表示;
00000080-000007FF的字符用兩個字節表示 (中文的編碼范圍)
轉換規則
0000~007F 1字節 0xxxxxxx
0080~07FF 2字節 110xxxxx 10xxxxxx
0800~FFFF 3字節 1110xxxx 10xxxxxx 10xxxxxx
4字節 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
5字節 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
6字節 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
python實現
輸入: 中文字符的unicode編碼,int型
輸出: utf-8編碼, str類型
如 '張',unicode編碼為0x5f20,輸入為0x5f20,輸出為0xe5bca0
def unicode_to_utf8(src):
ref = 0xe08080
result = ref
a = src & 0x3f //取最后六位
result = result | a //將最后六位放在ref最后六位的空位置
src = src >> 6
a = src & 0x3f //取接下來的六位
result = result | (a << 8) //放在ref對應的六個位置
src = src >> 6 //保留最后四位
result = result | (src << 16) //放在ref對應的四個位置
return "%x" % result