GBK转utf-8,宽字符转窄字符

时间:2023-03-08 18:38:39

//GBK转UTF8
string CAppString::GBKToUTF8(const string & strGBK)
{
string strOutUTF8 = "";
WCHAR * str1;
int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
str1 = new WCHAR[n];
MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
char * str2 = new char[n];
WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
strOutUTF8 = str2;
delete []str1;
str1 = NULL;
delete []str2;
str2 = NULL;
return strOutUTF8;
} //UTF8转GBK
string CAppString::UTF8ToGBK(const std::string & strUTF8)
{
int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);
unsigned short * wszGBK = new unsigned short[len + 1];
memset(wszGBK, 0, len * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)strUTF8.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;
std::string strTemp(szGBK);
delete[]szGBK;
delete[]wszGBK;
return strTemp;
} //宽字符转窄
string CAppString::Unicode2ACSII(const wstring & strSource)
{
string strDest("");
if (strSource.empty())
{
return strDest;
} int nlen = ::WideCharToMultiByte(CP_ACP, 0, strSource.c_str(), -1, NULL, 0, NULL, NULL);
char * szDest = new char[nlen + 1];
::WideCharToMultiByte(CP_ACP, 0, strSource.c_str(), -1, szDest, nlen, NULL, NULL);
strDest = szDest;
delete szDest;
szDest = NULL; return strDest;
} //窄字符转宽字符
wstring CAppString::ASCII2Unicode(const char* strSrc)
{
wchar_t* pElementText = NULL;
int nTextLen = 0;
// multi char to wide char
nTextLen = MultiByteToWideChar( CP_ACP, 0, strSrc, -1, NULL, 0 );
pElementText = new wchar_t[nTextLen + 1];
memset(( void* )pElementText, 0, sizeof( wchar_t ) * ( nTextLen + 1 ) );
::MultiByteToWideChar(CP_ACP, 0, strSrc, -1, pElementText, nTextLen);
wstring sText;
sText = pElementText;
delete[] pElementText;
return sText;
}