您的位置:首页 > 编程语言 > C语言/C++

C++编码转换函数代码

2016-06-14 01:34 465 查看
从原文转载: 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++