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


//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;
}

posted @   奥雷连诺  阅读(353)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
点击右上角即可分享
微信分享提示