c++之gbk和utf8编码转换

1.gbk转换成utf8

void GBKTOUTF8(string& strGBK)//转码 GBK编码转成UTF8编码
{
	int len = MultiByteToWideChar(CP_ACP,0, strGBK.c_str(), - 1, NULL, 0); 
	wchar_t* wszUtf8 = new wchar_t[len]; 
	memset(wszUtf8, 0, len);
	MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), - 1, wszUtf8, len); 
	len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL,0,NULL,NULL);
	char* szUtf8 = new char[len + 1];
	memset(szUtf8, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL, NULL);
	strGBK = szUtf8;
	delete[] szUtf8;
	delete[] wszUtf8;
}

2.utf8转换成gbk

std::string UTF8ToGBK(const char* strUTF8)//UTF8编码转成GBK编码
{
	int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, NULL, 0);
	wchar_t* wszGBK = new wchar_t[len + 1];
	memset(wszGBK,0, len * 2 + 2);
	MultiByteToWideChar(CP_UTF8,0, strUTF8, - 1, wszGBK, len); 
	len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
	char* szGBK = new char[len + 1];
	memset(szGBK,0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, wszGBK, - 1, szGBK,len, NULL, NULL); 
	std::string strTemp(szGBK);
	if (wszGBK) delete[] wszGBK;
	if (szGBK) delete[] szGBK;
	return strTemp;
}

猜你喜欢

转载自blog.csdn.net/weixin_62859191/article/details/128607240