VC++ UTF-8與GBK格式轉換

 1 // 註釋:多字節包括GBK和UTF-8  
 2 int GBK2UTF8(char *szGbk,char *szUtf8,int Len)  
 3 {  
 4     // 先將多字節GBK(CP_ACP或ANSI)轉換成寬字符UTF-16  
 5     // 獲得轉換後,所須要的內存字符數  
 6     int n = MultiByteToWideChar(CP_ACP,0,szGbk,-1,NULL,0);  
 7     // 字符數乘以 sizeof(WCHAR) 獲得字節數  
 8     WCHAR *str1 = new WCHAR[sizeof(WCHAR) * n];  
 9     // 轉換  
10     MultiByteToWideChar(CP_ACP,  // MultiByte的代碼頁Code Page  
11         0,            //附加標誌,與音標有關  
12         szGbk,        // 輸入的GBK字符串  
13         -1,           // 輸入字符串長度,-1表示由函數內部計算  
14         str1,         // 輸出  
15         n             // 輸出所需分配的內存  
16         );  
17   
18     // 再將寬字符(UTF-16)轉換多字節(UTF-8)  
19     n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);  
20     if (n > Len)  
21     {  
22         delete[]str1;  
23         return -1;  
24     }  
25     WideCharToMultiByte(CP_UTF8, 0, str1, -1, szUtf8, n, NULL, NULL);  
26     delete[]str1;  
27     str1 = NULL;  
28   
29     return 0;  
30 }  
 1 //UTF-8 GBK  
 2 int UTF82GBK(char *szUtf8,char *szGbk,int Len)  
 3 {  
 4     int n = MultiByteToWideChar(CP_UTF8, 0, szUtf8, -1, NULL, 0);  
 5     WCHAR * wszGBK = new WCHAR[sizeof(WCHAR) * n];  
 6     memset(wszGBK, 0, sizeof(WCHAR) * n);  
 7     MultiByteToWideChar(CP_UTF8, 0,szUtf8,-1, wszGBK, n);  
 8   
 9     n = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);  
10     if (n > Len)  
11     {  
12         delete[]wszGBK;  
13         return -1;  
14     }  
15   
16     WideCharToMultiByte(CP_ACP,0, wszGBK, -1, szGbk, n, NULL, NULL);  
17   
18     delete[]wszGBK;  
19     wszGBK = NULL;  
20   
21     return 0;  
22 }
相關文章
相關標籤/搜索