WIN32下C语言的编码转换

 1 char* Unicode2Utf8(const char* unicode)
 2 {
 3     int len;
 4     len = WideCharToMultiByte(CP_UTF8, 0, (const wchar_t*)unicode, -1, NULL, 0, NULL, NULL);
 5     char *szUtf8 = (char*)malloc(len + 1);
 6     memset(szUtf8, 0, len + 1);
 7     WideCharToMultiByte(CP_UTF8, 0, (const wchar_t*)unicode, -1, szUtf8, len, NULL,NULL);
 8     return szUtf8;
 9 }
10 
11 char* Ansi2Unicode(const char* str)
12 {
13     int dwUnicodeLen = MultiByteToWideChar(CP_ACP,0,str,-1,NULL,0);
14     if(!dwUnicodeLen)
15     {
16         return strdup(str);
17     }
18     size_t num = dwUnicodeLen*sizeof(wchar_t);
19     wchar_t *pwText = (wchar_t*)malloc(num);
20     memset(pwText,0,num);
21     MultiByteToWideChar(CP_ACP,0,str,-1,pwText,dwUnicodeLen);
22     return (char*)pwText;
23 }
24 
25 char* ConvertAnsiToUtf8(const char* str)
26 {
27     char* unicode = Ansi2Unicode(str); 
28     char* utf8 = Unicode2Utf8(unicode);
29     free(unicode);
30     return utf8;
31 }

好不容易找到能用的,赶紧拿小本本记下来。

posted on 2017-09-13 15:18  冰霁  阅读(334)  评论(0)    收藏  举报

导航