从原文转载: http://www.2cto.com/database/201411/354891.html
//UTF-8转Unicode
std::wstring Utf82Unicode(conststd::string& utf8string)
{
intwidesize =::MultiByteToWideChar(CP_UTF8, 0, utf8string.c_str(), -1, NULL, 0);
if (widesize ==ERROR_NO_UNICODE_TRANSLATION)
{
throw std::exception("Invalid UTF-8sequence.");
}
if (widesize == 0)
{
throw std::exception("Error inconversion.");
}
std::vector<wchar_t>resultstring(widesize);
intconvresult =::MultiByteToWideChar(CP_UTF8, 0, utf8string.c_str(), -1, &resultstring[0],widesize);
if (convresult != widesize)
{
throw std::exception("Lafalla!");
}
returnstd::wstring(&resultstring[0]);
}
//unicode转为 ascii
string WideByte2Acsi(wstring& wstrcode)
{
intasciisize =::WideCharToMultiByte(CP_OEMCP, 0, wstrcode.c_str(), -1, NULL, 0, NULL, NULL);
if (asciisize ==ERROR_NO_UNICODE_TRANSLATION)
{
throw std::exception("Invalid UTF-8sequence.");
}
if (asciisize == 0)
{
throw std::exception("Error inconversion.");
}
std::vector<char>resultstring(asciisize);
intconvresult=::WideCharToMultiByte(CP_OEMCP, 0, wstrcode.c_str(), -1, &resultstring[0],asciisize, NULL, NULL);
if (convresult != asciisize)
{
throw std::exception("Lafalla!");
}
returnstd::string(&resultstring[0]);
}
//utf-8转 ascii
string UTF_82ASCII(string& strUtf8Code)
{
string strRet("");
//先把 utf8 转为 unicode
wstring wstr = Utf82Unicode(strUtf8Code);
//最后把 unicode 转为 ascii
strRet = WideByte2Acsi(wstr);
returnstrRet;
}
//ascii转 Unicode
wstring Acsi2WideByte(string& strascii)
{
intwidesize =MultiByteToWideChar (CP_ACP, 0, (char*)strascii.c_str(), -1, NULL, 0);
if (widesize ==ERROR_NO_UNICODE_TRANSLATION)
{
throw std::exception("Invalid UTF-8sequence.");
}
if (widesize == 0)
{
throw std::exception("Error inconversion.");
}
std::vector<wchar_t>resultstring(widesize);
intconvresult =MultiByteToWideChar (CP_ACP, 0, (char*)strascii.c_str(), -1,&resultstring[0], widesize);
if (convresult != widesize)
{
throw std::exception("Lafalla!");
}
returnstd::wstring(&resultstring[0]);
}
//Unicode转 Utf8
std::string Unicode2Utf8(conststd::wstring& widestring)
{
intutf8size =::WideCharToMultiByte(CP_UTF8, 0, widestring.c_str(), -1, NULL, 0, NULL, NULL);
if (utf8size == 0)
{
throw std::exception("Error inconversion.");
}
std::vector<char>resultstring(utf8size);
intconvresult =::WideCharToMultiByte(CP_UTF8, 0, widestring.c_str(), -1, &resultstring[0],utf8size, NULL, NULL);
if (convresult != utf8size)
{
throw std::exception("Lafalla!");
}
returnstd::string(&resultstring[0]);
}
//ascii转 Utf8
string ASCII2UTF_8(string&strAsciiCode)
{
string strRet("");
//先把 ascii 转为 unicode
wstring wstr = Acsi2WideByte(strAsciiCode);
//最后把 unicode 转为 utf8
strRet = Unicode2Utf8(wstr);
returnstrRet;
}