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 }
时间: 2024-10-06 05:02:25