utf8与gbk字符之间的转换主要用到两个方法
WideCharToMultiByte:http://baike.baidu.com/view/2083430.htm?fr=aladdin
MultiByteToWideChar:http://baike.baidu.com/view/1907282.htm?fr=aladdin
使用这两个方法就可以成功转换。
将GBK转换成UTF8
std::string GBKtoUTF8(const std::string& str)
{
std::string strout = "";
WCHAR * strGBK;
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
strGBK = new WCHAR[len];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, strGBK, len);
len = WideCharToMultiByte(CP_UTF8, 0, strGBK, -1, NULL, 0, NULL, NULL);
char * strUTF8 = new char[len];
WideCharToMultiByte(CP_UTF8, 0, strGBK, -1, strUTF8, len, NULL, NULL);
//memcpy(str, strUTF8, strlen(strUTF8));
strout = strUTF8;
delete[] strGBK;
strGBK = NULL;
delete[] strUTF8;
strUTF8 = NULL;
return strout;
}
将UTF8转换成GBK
std::string UTF8toGBK(const std::string& strint)
{
std::string strout = "";
int len = MultiByteToWideChar(CP_UTF8, 0, strint.c_str(), -1, NULL, 0);
unsigned short * wszGBK = new unsigned short[len + 1];
memset(wszGBK, 0, len * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, strint.c_str(), -1, (LPWSTR)wszGBK, len);
len = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)wszGBK, -1, NULL, 0, NULL, NULL);
char *szGBK = new char[len + 1];
memset(szGBK, 0, len + 1);
WideCharToMultiByte(CP_ACP,0, (LPWSTR)wszGBK, -1, szGBK, len, NULL, NULL);
//strUTF8 = szGBK;
//memcpy(strout, szGBK, strlen(szGBK));
strout = szGBK;
delete[]szGBK;
delete[]wszGBK;
return strout;
}
最后
以上就是知性白羊最近收集整理的关于UTF8与GBK字符编码转换的全部内容,更多相关UTF8与GBK字符编码转换内容请搜索靠谱客的其他文章。
发表评论 取消回复