C++编码转换函数代码

来源:互联网 发布:蚂蚁系统分类数据调用 编辑:程序博客网 时间:2024/06/06 19:52

从原文转载: http://www.2cto.com/database/201411/354891.html

//UTF-8转Unicodestd::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转为 asciistring 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转 asciistring UTF_82ASCII(string& strUtf8Code){string strRet("");//先把 utf8 转为 unicodewstring wstr = Utf82Unicode(strUtf8Code);//最后把 unicode 转为 asciistrRet = WideByte2Acsi(wstr);returnstrRet;}
//ascii转 Unicodewstring 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转 Utf8std::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转 Utf8string ASCII2UTF_8(string&strAsciiCode){string strRet("");//先把 ascii 转为 unicodewstring wstr = Acsi2WideByte(strAsciiCode);//最后把 unicode 转为 utf8strRet = Unicode2Utf8(wstr);returnstrRet;}
0 0
原创粉丝点击