unicode轉utf-8
在使用C呼叫python模組的時候發生了慘案,模組回傳了"編碼字串" \u4e09\u5929\u4e09\u591c (e.g. "三天三夜"對應"\u4e09\u5929\u4e09\u591c")。為此我只好自行轉換了。
由於系統使用utf-8編碼。所以把根據下表把unicode所在的範圍轉成對應的utf8格式即可。就可以正常顯示囉!
| UCS-4 編碼 | UTF-8 編碼 |
|---|---|
| 00000000 - 0000007F | 0xxxxxxx |
| 00000080 - 000007FF | 110xxxxx 10xxxxxx |
| 00000800 - 0000FFFF | 1110xxxx 10xxxxxx 10xxxxxx |
| 00010000 - 001FFFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
| 00200000 - 03FFFFFF | 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
| 04000000 - 7FFFFFFF | 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
Example
#include <stdio.h>
int main()
{
const char *szUniStr = "\u4e09\u5929\u4e09\u591c";
printf("%s\n", szUniStr);
const char szUtf8[] = { \
0xe4, 0xb8, 0x89, \
0xe5, 0xa4, 0xa9, \
0xe4, 0xb8, 0x89, \
0xe5, 0xa4, 0x9c, \
};
printf("%s\n", szUtf8);
}
----------
yijyundeMacBook-Pro:c yijyun$ ./a.out
三天三夜
三天三夜
留言
張貼留言