如下是一段本地编码到unicode以及utf-8编码的转换代码.是基于STL 的string类的.使用了windows的API :
MultiByteToWideChar和WideCharToMultiByte.故它只能在windows平台下使用.
这里没有针对超长的字符串转换作优化,不能保证转换大段数据时的效率.
#include <string>
#include <windows.h>
// 其它辅助函数:编码转换
static std::wstring mb2wc(const std::string &strC,UINT CodePage= CP_ACP);
static std::string wc2mb(const std::wstring &strW,UINT CodePage= CP_ACP);
using namespace std;
wstring mb2wc(const string &strC,UINT CodePage)
{
const int strlen = strC.size();
int nNeedSize = MultiByteToWideChar(CodePage,0,strC.c_str(),strlen,NULL,0);
if(nNeedSize<=0)
return wstring();
wchar_t *pWChar = new wchar_t[nNeedSize+1];
int nRetSize = MultiByteToWideChar(CodePage,0,strC.c_str(),strlen,pWChar,nNeedSize);
if(nRetSize<=0){
delete[] pWChar;
return wstring();
}
wstring ss(pWChar,nRetSize);
delete[] pWChar;
return ss;
}
string wc2mb(const wstring &strW,UINT CodePage)
{
const int strlen = strW.size();
int nNeedSize = WideCharToMultiByte(CodePage,0,strW.c_str(),strlen,NULL,0,NULL,NULL);
if(nNeedSize<=0)
return string();
char *pStr = new char[nNeedSize+1];
int nRetSize = WideCharToMultiByte(CodePage,0,strW.c_str(),strlen,pStr,nNeedSize,NULL,NULL);
if(nRetSize<=0){
delete[] pStr;
return string();
}
string ss(pStr,nRetSize);
delete[] pStr;
return ss;
}