C++ GB2312 和 utf8 在win32下 互转

 1 string ANSItoUTF8(const char* strAnsi)
 2 {
 3     //获取转换为宽字节后需要的缓冲区大小,创建宽字节缓冲区,936为简体中文GB2312代码页  
 4     int nLen = MultiByteToWideChar(CP_ACP, NULL, strAnsi, -1, NULL, NULL);
 5     WCHAR *wszBuffer = new WCHAR[nLen + 1];
 6     nLen = MultiByteToWideChar(CP_ACP, NULL, strAnsi, -1, wszBuffer, nLen);
 7     wszBuffer[nLen] = 0;
 8     //获取转为UTF8多字节后需要的缓冲区大小,创建多字节缓冲区  
 9     nLen = WideCharToMultiByte(CP_UTF8, NULL, wszBuffer, -1, NULL, NULL, NULL, NULL);
10     CHAR *szBuffer = new CHAR[nLen + 1];
11     nLen = WideCharToMultiByte(CP_UTF8, NULL, wszBuffer, -1, szBuffer, nLen, NULL, NULL);
12     szBuffer[nLen] = 0;
13 
14     string s1 = szBuffer;
15     //内存清理  
16     delete[]wszBuffer;
17     delete[]szBuffer;
18     return s1;
19 }
20 
21 string UTF8toANSI(const char* strUTF8)
22 {
23     //获取转换为多字节后需要的缓冲区大小,创建多字节缓冲区  
24     int nLen = MultiByteToWideChar(CP_UTF8, NULL, strUTF8, -1, NULL, NULL);
25     WCHAR *wszBuffer = new WCHAR[nLen + 1];
26     nLen = MultiByteToWideChar(CP_UTF8, NULL, strUTF8, -1, wszBuffer, nLen);
27     wszBuffer[nLen] = 0;
28 
29     nLen = WideCharToMultiByte(936, NULL, wszBuffer, -1, NULL, NULL, NULL, NULL);
30     CHAR *szBuffer = new CHAR[nLen + 1];
31     nLen = WideCharToMultiByte(936, NULL, wszBuffer, -1, szBuffer, nLen, NULL, NULL);
32     szBuffer[nLen] = 0;
33 
34     string s1 = szBuffer;
35     //清理内存  
36     delete[]szBuffer;
37     delete[]wszBuffer;
38     return s1;
39 }

转载

posted @ 2018-02-06 16:53  花园小花匠  阅读(1252)  评论(0编辑  收藏  举报